- 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();
- }
- }
- }
- }
Android的SurfaceView绘图并移动
最新推荐文章于 2022-05-09 23:23:59 发布