SurfaceView use
android.view.SurfaceView is commonly used in game development framework , he inherited android.view.View, compared with View , surfaceView is starting in a new separate thread can redraw the screen while the View must be the main thread of the UI update screen . Therefore, development of the game , if the interface is required to use initiative to update SurfaceView ( eg racing , you need a separate thread to update the interface to prevent the main thread is blocked ) , a passive update ( board game ) can use the View frame ( call invalidate method to update ) .
described above rough SurfaceView and View. Here is a simple example to illustrate SurfaceView.
create a MySurfaceView.java
public class MySurfaceView extends SurfaceView implements Callback, Runnable { // 打开程序后,创建一个矩形,并让矩形随着时间而移动
int x = 0, y = 0, w = 40, h = 40, SrceenW, SrceenH; // 定义矩形的x,y坐标,宽高,以及手机的屏幕宽高
SurfaceHolder surfaceHolder;
Thread thread; // 定义一个线程,用来更新矩形所在的位置
int sleepTime = 100;// 让线程100毫秒更新一次界面
Paint paint; // 画笔
boolean flag = false;// 线程是否启动
public MySurfaceView(Context context, int SrceenW, int SrceenH) {
super(context);
surfaceHolder = getHolder();
surfaceHolder.addCallback(this);
this.SrceenH = SrceenH;
this.SrceenW = SrceenW;
paint = new Paint();
thread = new Thread(this);
}
/**
*
*/
public void draw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
paint.setColor(Color.RED);
canvas.drawRect(x, y, x + w, y + h, paint);
}
/**
* 逻辑
*/
public void logic() {
if(x<=0){
x=0;
}
if(y<=0){
y=0;
}
if(x>=SrceenW-w){
x=SrceenW-w;
}
if(y>=SrceenH-h){
y=SrceenH-h;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) { // 启动线程绘制
// TODO Auto-generated method stub
flag = true;
if (!thread.isAlive()) {
thread.start();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) { // 结束线程绘制
// TODO Auto-generated method stub
flag = false;
thread = null;
}
@Override
public void run() { // 绘制的更新过程
// TODO Auto-generated method stub
Canvas canvas = null;
while (flag) {
try {
canvas = surfaceHolder.lockCanvas(); //锁定画布开始绘制
synchronized (canvas) {
logic();
draw(canvas);
}
} catch (Exception e) {
Log.e("mysurfaceview",e.getMessage());
}finally{
if(canvas!=null){
surfaceHolder.unlockCanvasAndPost(canvas);//解锁画布结束绘制
}
}
x++; //x,y坐标改变
y++;
try {
Thread.sleep(sleepTime); //阻塞线程
} catch (Exception e) {
Log.e("mysurfaceview",e.getMessage());
}
}
}
Activity Calling
public class SurfaceActivty extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// 获取屏幕宽高
Display display = getWindowManager().getDefaultDisplay();
setContentView(new MySurfaceView(this,display.getWidth(),display.getHeight()));
}
}
没有评论:
发表评论