80,447
社区成员
发帖
与我相关
我的任务
分享
public class MainActivity extends Activity implements Runnable {
Button button;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
Thread thread;
private final String TAG = "MainActivity.java";
private boolean isStarted = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
button = (Button) findViewById(R.id.button1);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
thread = new Thread(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!isStarted) {
isStarted = true;
thread.start();
}
}
});
}
@Override
public void run() {
// TODO Auto-generated method stub
if (surfaceHolder == null) {
Log.i(TAG, "surfaceHolder==null");
return;
}
int i = 0;
Paint mPaint = new Paint();
mPaint.setColor(Color.WHITE);// 画笔为绿色
mPaint.setStrokeWidth(2);// 设置画笔粗细
mPaint.setTextSize(50);;
while (i < 20) {
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawText(""+i, 100, 50+50*i, mPaint);
surfaceHolder.unlockCanvasAndPost(canvas);// 解锁画布,提交画好的图像
i++;
try {
thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="22dp"
android:text="开始" />
<SurfaceView
android:layout_below="@id/button1"
android:id="@+id/surfaceView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
研究了下你这个现象,我的理解是这样的:
目前的Android版本是3缓冲,也就是有3个buffer用于绘制.
一对lockCanvas和unlockCanvasAndPost操作一般是一次完整的绘制操作,该操作后就会切换buffer(缓冲)
所以你循环20次该操作,本身的意义也就是在于最后最后一次绘制结果,
所以正常情况下,你期望应该是最后一次绘制结果 "19"
所以前面的数字只是之前绘制在该buffer上的数字,所以是随机的,但最终一定是19
而如果想要去除前面的绘制,应该在绘制前主动清理,如:
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);