SurfaceView小记

在开发android手机游戏要实现复杂一点的动画效果时,常常用到SurfaceView而不是View(当然View也可以实现复杂的动画),

SufaceView与View相比有一些特点:

  • 使用SurfaceView开发时可以直接获得Canvas对象,而不像View要在onDraw方法中获得Canvas对象。
  • SurfaceView支持双缓冲技术,绘制图形的效率更高。
  • SurfaceView可以在非UI线程中直接绘制图形,而View必须要使用Handler对象发送消息,通知UI线程绘制图形。                                                                                                继承了SurfaceView的子类必须实现SurfaceHolderCallback接口。该接口要实现三个方法                                                                                                                                               1.surfaceCreated:
              2.surfaceChanged
              3.surfaceDestroyed
下面用一个例子展示SurfaceView的基本用法。在例子中用SurfaceView的SurfaceCreated方法来调用OnDraw方法来绘制圆 SurfaceView小记_第1张图片
public class MySurfaceViewActivity extends SurfaceView implements 
SurfaceHolder.Callback,OnTouchListener {

	public float x;
	public float y;
	private SurfaceHolder surfaceHolder;
	
	public MySurfaceViewActivity(Context context) {
		super(context);
		setOnTouchListener(this);
		surfaceHolder = this.getHolder();
		surfaceHolder.addCallback(this);
		this.setFocusable(true);
		
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		drawCircle();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onTouch(View view, MotionEvent event) {
		AnimThread animThread = new AnimThread(event.getX(),event.getY());
		Thread thread = new Thread(animThread);
		thread.start();
		return false;
	}
	class AnimThread implements Runnable
	{
		private float newX,newY;
		public AnimThread(float newX,float newY ){
			this.newX=newX;
			this.newY=newY;
		}
		@Override
		public void run() {
			float scale = Math.abs(y-newY)/Math.abs(x-newX);
			while(newX!=x&&newY!=y)
			{
				if(newX > x)
				{
					x+=1;
					if(newX<x){
						x=newX;
					}
				}
				else if(newX<x)
				{
					x-=1;
					if(newX>x)
					{
						x=newX;
					}
				}
				
				if(newY >y)
				{
					y+=scale;
					if(newY<y)
					{
						y=newY;
					}
				}
				else if(newY<y)
				{
					y-=scale;
					if(newY >y)
						y=newY;
				}
				
				try
				{
					drawCircle();
					Thread.sleep(50);
				}
				catch (Exception e)
				{
					
				}
			} 
		}
		
	}
	public void drawCircle(){
		if(surfaceHolder == null)
		{
			return;
		}
		Canvas canvas = surfaceHolder.lockCanvas();
		canvas.drawColor(Color.BLUE);
		if (canvas==null)
		{
			return;
		}
		Paint p = new Paint();
		p.setColor(Color.YELLOW);
		canvas.drawCircle(x, y, 20, p);
		surfaceHolder.unlockCanvasAndPost(canvas);
	}

}


        

你可能感兴趣的:(SurfaceView小记)