android游戏开发学习笔之七 (学习书籍 Android游戏编程之从零开始)

/**
* 可视区域
*
* @time 上午10:42:39
* @author retacn yue
* @Email [email protected]
*/
@SuppressWarnings("unused")
public class ClipCanvasSurfaceView extends SurfaceView implements Callback, Runnable {
private boolean flag;// surfaceView状态标志位
private SurfaceHolder sfh;
private Paint paint;
private Bitmap bitmap;
private Thread thread;
private Canvas canvas;


private int screenX, screenY;


public ClipCanvasSurfaceView(Context context) {
super(context);
/********** 画图所必需 *********************/
sfh = this.getHolder();// 获得surfaceHolder对象
sfh.addCallback(this);


thread = new Thread(this);


paint = new Paint();// 新建画笔
paint.setColor(Color.WHITE);// 设置画笔颜色
paint.setAntiAlias(true);// 消除锯齿


this.setKeepScreenOn(true);// 保持屏幕常亮
this.setFocusable(true);
/********************************************/
bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.icon);


}


@SuppressWarnings("static-access")
@Override
public void run() {
while (flag) {
// 绘图
draw();
try {
thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}


}


/**
* 绘图
*/
private void draw() {
try {
canvas = sfh.lockCanvas();
if (null != canvas) {
// 填充,充当刷屏
canvas.drawColor(Color.BLACK);
// 矩形可见区域
/*
* canvas.save(); canvas.clipRect(0, 0, 20, 20);//矩形大小
* canvas.drawBitmap(bitmap, 0, 0, paint); canvas.restore();
*/
// 利用path设置可见区域
/*
* canvas.save(); Path path=new Path(); path.addCircle(30, 30,
* 30, Direction.CCW); canvas.clipPath(path);
* canvas.drawBitmap(bitmap, 10, 10, paint);
*/
// 利用region设置可视区域
canvas.save();
Region region = new Region();
region.op(new Rect(20, 20, 100, 100), Region.Op.UNION);
region.op(new Rect(40, 20, 80, 150), Region.Op.XOR);
canvas.clipRegion(region);
canvas.drawBitmap(bitmap, 0, 0, paint);
canvas.restore();
}


} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != canvas) {
sfh.unlockCanvasAndPost(canvas);
}
}


}


/**
* 游戏逻辑
*/
private void logic() {


}


/**
* 创建surfaceView时使用
*/
@Override
public void surfaceCreated(SurfaceHolder holder) {
screenX = this.getWidth();
screenY = this.getHeight();
flag = true;
// 实例化线程
thread = new Thread(this);
thread.start();
}


/**
* 改变时调用
*/
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {


}


/**
* 销毁时调用
*/
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
flag = false;
}


}

猜你喜欢

转载自201206260201.iteye.com/blog/1688835