利用surfaceview问题

时间:2012-07-22 13:31:07

标签: android canvas surfaceview runnable

我尝试使用画布在surfaceview上绘制文本。 问题是每次调用后,surfaceview似乎都没有重置。所有被吸引的东西都将被重新绘制。所以,如果我有一个文本,我每次都会改变它的位置,我最终得到了一段长文本,因为画布未被清除。

我做错了什么?

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);
            }
        }
    }

}

谢谢!

2 个答案:

答案 0 :(得分:1)

在画画之前你必须先画布画布。 canvas.drawColor(Color.BLACK);

  • ereas(画黑)
  • 绘制文字

注意:不要在更新和渲染线程中创建一个Paint对象,它会让GC疯狂!

答案 1 :(得分:0)

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