2012-07-22 66 views
0

我试图使用画布在surfaceview上绘制文本。 问题在于每次调用后Surfaceview似乎都不会重置。所有被掠夺的东西都会被再次绘制。所以,如果我有一个文本可以改变它被绘制的每一次的位置,那么我最终会得到很长的一段文字,因为canvas没有清除。绘制表面问题

我在做什么错?

public class Test1Activity extends Activity { 

private Draw drawText; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    drawText = new Draw(this); 
    setContentView(drawText); 
} 

public class Draw extends SurfaceView implements Runnable { 

    Thread thread = null; 
    SurfaceHolder surfaceHolder; 
    volatile boolean running = false; 
    private int i; 

    public Draw(Context context) { 
     super(context); 
     // TODO Auto-generated constructor stub 
     surfaceHolder = getHolder(); 
     running = true; 
     thread = new Thread(this); 
     thread.start(); 
    } 


    public void run() { 
     // TODO Auto-generated method stub 
     while (running) { 
      if (surfaceHolder.getSurface().isValid()) { 
       Canvas canvas = surfaceHolder.lockCanvas(); 

       Paint paint = new Paint(); 
       paint.setColor(Color.RED); 
       i++; 
       if(i > 240) 
        i = 1; 

       canvas.drawText("Hello",i , 60, paint); 

       surfaceHolder.unlockCanvasAndPost(canvas); 
      } 
     } 
    } 

} 
}  

public class Test1Activity extends Activity { 


private Draw drawText; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    drawText = new Draw(this); 
    setContentView(drawText); 
} 



public class Draw extends SurfaceView implements Runnable { 

    Thread thread = null; 
    SurfaceHolder surfaceHolder; 
    volatile boolean running = false; 
    private int i; 

    public Draw(Context context) { 
     super(context); 
     // TODO Auto-generated constructor stub 
     surfaceHolder = getHolder(); 
     running = true; 
     thread = new Thread(this); 
     thread.start(); 
    } 


    public void run() { 
     // TODO Auto-generated method stub 
     while (running) { 
      if (surfaceHolder.getSurface().isValid()) { 
       Canvas canvas = surfaceHolder.lockCanvas(); 

       Paint paint = new Paint(); 
       paint.setColor(Color.RED); 
       i++; 
       if(i > 240) 
        i = 1; 

       canvas.drawText("Hello",i , 60, paint); 

       surfaceHolder.unlockCanvasAndPost(canvas); 
      } 
     } 
    } 

} 

谢谢!

回答

1

在绘制某些东西之前,您必须先画好画布。 canvas.drawColor(Color.BLACK);

  • ereas(绘制黑色)
  • 画文本

注意:不要在你的更新和渲染线程创建一个喷漆的对象,这将带动GC疯了!

0

您是否需要在不同的PorterDuff模式下重绘过时的画布。 this link很有用。