View Code
package xl.test;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class ViewTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
//視圖内部類
class MyView extends SurfaceView implements SurfaceHolder.Callback
{
private SurfaceHolder holder;
private MyThread myThread;
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder = this.getHolder();
holder.addCallback(this);
myThread = new MyThread(holder);//建立一個繪圖線程
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
public void surfaceCreated(SurfaceHolder holder) {
myThread.isRun = true;
myThread.start();
public void surfaceDestroyed(SurfaceHolder holder) {
myThread.isRun = false;
//線程内部類
class MyThread extends Thread
public boolean isRun ;
public MyThread(SurfaceHolder holder)
this.holder =holder;
isRun = true;
public void run()
int count = 0;
while(isRun)
Canvas c = null;
try
synchronized (holder)
c = holder.lockCanvas();//鎖定畫布,一般在鎖定後就可以通過其傳回的畫布對象Canvas,在其上面畫圖等操作了。
c.drawColor(Color.BLACK);//設定畫布背景顔色
Paint p = new Paint(); //建立畫筆
p.setColor(Color.WHITE);
Rect r = new Rect(100, 50, 300, 250);
c.drawRect(r, p);
c.drawText("這是第"+(count++)+"秒", 100, 310, p);
Thread.sleep(1000);//睡眠時間為1秒
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
finally
if(c!= null)
holder.unlockCanvasAndPost(c);//結束鎖定畫圖,并送出改變。