- import android.app.Activity;
- import android.content.Context;
- import android.graphics.*;
- import android.os.Bundle;
- import android.view.*;
- public class Mian extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- MyView my=new MyView(this);
- setContentView(my);
- }
- }
- class MyView extends SurfaceView implements SurfaceHolder.Callback,Runnable
- {
- SurfaceHolder holder;
- Rect rect;//建立類
- public MyView(Context context)
- {
- super(context);
- holder = this.getHolder();//獲取SurfaceHolder對象實例
- holder.addCallback(this);//添加callback接口
- setFocusable(true);
- rect=new Rect(150, 150);
- Thread t=new Thread(rect);
- t.start();
- }
- @Override
- //當SurfaceView尺寸改變時調用
- public void surfaceChanged(SurfaceHolder holder, int format, int width,int height){}
- @Override
- //當SurfaceView建立時調用
- public void surfaceCreated(SurfaceHolder holder)
- {
- new Thread(this).start();//啓動新的線程
- }
- //當SurfaceView銷燬時調用
- @Override
- public void surfaceDestroyed(SurfaceHolder holder){}
- @Override
- public synchronized void run() {
- // TODO Auto-generated method stub
- while(true){
- Canvas canvas = holder.lockCanvas(null);//SurfaceHolder鎖定並得到canvas對象
- canvas.drawColor(Color.WHITE);
- this.drawGraphics(canvas);
- holder.unlockCanvasAndPost(canvas);//解鎖畫布,提交畫好的圖像
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- public void drawGraphics(Canvas canvas){
- Paint mPaint = new Paint();
- mPaint.setStyle(Paint.Style.FILL);//設置爲實心
- mPaint.setColor(Color.RED);
- mPaint.setAntiAlias(true);//設置抗鋸齒
- this.draw(canvas, mPaint);
- }
- public void draw(Canvas canvas,Paint p){
- canvas.drawCircle(100, rect.y, 50, p);//畫圓
- }
- }
- class Rect implements Runnable{ //矩形類
- int x;
- int y;
- int speed=10;
- public Rect(int x,int y){
- this.x=x;
- this.y=y;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- while(true){
- y+=speed;
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
本文同步分享在 博客「xiangzhihong8」(CSDN)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。android