兩個矩形不斷作變化
package com.example.mysurfacetest;
import ....
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//將主程式畫面設給繼承SurfaceView的自建內部類別
setContentView(new MySurface(this));
}
//自建內部類別必須繼承SurfaceView以及實作SurfaceHolder.Callback
//並實作其抽象Callback方法
public class MySurface extends SurfaceView implements
SurfaceHolder.Callback {
//建立以及宣告Handler來管理以及調派執行緒
final private Handler handler = new Handler();
//宣告SurfaceHolder,之後用來取得Canvas物件
SurfaceHolder holder;
boolean flag;
//宣告畫筆變數以及建立物件
Paint mPaint = new Paint();
//建構式
public MySurface(Context context) {
super(context);
// TODO Auto-generated constructor stub
//取得SurfaceHolder物件
holder = this.getHolder();
//addCallback()設定callback函式
holder.addCallback(this);
flag = true;
}
//繪圖的工作在自建執行緒t中執行
Thread t = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
drawPicture();
}
});
//Callback
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
//Callback
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
//啟動執行緒
t.start();
}
//Callback
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
handler.removeCallbacks(t);
}
protected void drawPicture() {
// TODO Auto-generated method stub
// Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
//鎖定畫布,並利用SurfaceHolder取得canvas物件
Canvas c = holder.lockCanvas();
if (flag) {
mPaint.setColor(Color.RED);
// c.drawBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), null);
//用Canvas繪圖
//RectF(原點X軸,原點Y軸,寬,高)
c.drawRect(new RectF(0, 100, 1200, 600), mPaint);
flag = false;
} else {
mPaint.setColor(Color.BLUE);
c.drawRect(new RectF(380, 380, 760, 760), mPaint);
flag = true;
}
//解鎖畫布
holder.unlockCanvasAndPost(c);
//執行緒t暫停1秒後再跑一次
handler.postDelayed(t, 1000);
}
}
}
沒有留言:
張貼留言