package yxqz.com;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
/**
* android surfaceview简单的图片绘制
* @author mahaile
*
*/
public class GameSurfaceView extends SurfaceView implements Callback {
boolean flag; //线程标示位 当为false时停止刷新界面
SurfaceHolder surfaceHolder;
GameViewThread gameViewThread;
int x,y;
int direction=0; //图片运行方向 控制图片向上 或向下运动
int width,height;
Bitmap bitmap_role;
public GameSurfaceView(Context context) {
super(context);
surfaceHolder=this.getHolder();
surfaceHolder.addCallback(this); //添加回调
bitmap_role=BitmapFactory.decodeResource(getResources(), R.drawable.role);
}
public void onDraw(Canvas canvas){
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bitmap_role, width/2-bitmap_role.getWidth()/2, y, null);
}
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
}
public void surfaceCreated(SurfaceHolder surfaceHolder) {
//获取屏幕的 宽高 只有在 surface创建的时候 才有效 ,才构造方法中获取 宽高是获取不到的
width=this.getWidth();
height=this.getHeight();
//初始化绘图线程
gameViewThread=new GameViewThread();
gameViewThread.flag=true;
gameViewThread.start();
}
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
gameViewThread.flag=false; //销毁线程
}
class GameViewThread extends Thread{
public boolean flag;
public void run(){
while(flag){
Canvas canvas=null;
try{
if(direction==0){
if(y>=height){
direction=1;
}
y+=1;
}else{
if(y<=0){
direction=0;
}
y-=1;
}
canvas=surfaceHolder.lockCanvas(); //锁定画布 并获取canvas
onDraw(canvas);//调用onDraw 渲染到屏幕
surfaceHolder.unlockCanvasAndPost(canvas); //此步不要忘记了喔 否则界面上显示不出来的
}catch(Exception e){
e.printStackTrace();
}
try {
Thread.sleep(10);//线程休眠时间 控制帧数
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //每一秒刷新一次
}
}
}
}
评论5
最新资源