android surfaceView 指哪画哪demo

以下为surfaceView 的demo 希望给初学者带来点帮助
首先先建立一个activity,然后建立一个view 继承surfaceView
package com.logan.androidtest;

import android.app.Activity;
import android.os.Bundle;

import com.logan.androidtest.view.GameSurfaceView;
/**
 * 
 * @author xuan.lx
 *
 */
public class GameSurfaceViewActivity extends Activity {
	public static float y = 0;
	public static float x = 0;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		GameSurfaceView view = new GameSurfaceView(this);
		setContentView(view);
	}



}
package com.logan.androidtest.view;

import com.logan.androidtest.Constant;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * 
 * @author xuan.lx
 *
 */
public class GameSurfaceView extends SurfaceView implements
		SurfaceHolder.Callback {

	public static float y = 0;
	public static float x = 0;
	SurfaceView surfaceView;
	SurfaceHolder sfh;

	public GameSurfaceView(Context context) {
		super(context);
		sfh = this.getHolder();// 获取holder
		sfh.addCallback(this);

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		new DrawImage().start();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {

	}

	/**
	 * 绘图线程
	 */
	class DrawImage extends Thread {
		public void run() {
			// 绘图
			Paint mPaint = new Paint();
			mPaint.setColor(Color.BLUE);
			Canvas c = sfh.lockCanvas(null);
			c.drawColor(Color.BLACK);// 清除画布   
			c.drawRect(x, y, x + 40, y + 40, mPaint);
			sfh.unlockCanvasAndPost(c);// 更新屏幕显示内容
			Log.e(Constant.TAG = "ControlViewView", "DrawImage");

		}

	}

	// 触摸事件
	public boolean onTouchEvent(MotionEvent event) {
		y = event.getY();
		x = event.getX();
		new DrawImage().start();
		return true;
	}
	

}
android surfaceView 指哪画哪demo

你可能感兴趣的:(SurfaceView)