Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android SurfaceView使用例子

android SurfaceView使用例子

編輯:關於Android編程

做游戲一般用SurfaceView

[java] 
package com.himi;  
import android.content.Context;  
import android.graphics.Canvas;  
import android.graphics.Color;  
import android.graphics.Paint;  
import android.view.SurfaceHolder;  
import android.view.SurfaceView;  
import android.view.SurfaceHolder.Callback;  
import android.view.animation.Animation;  
/** 
* @author Himi 
*/  
public class MySurfaceView extends SurfaceView implements Callback, Runnable {// 備注1  
private SurfaceHolder sfh;  
private Thread th;  
private Canvas canvas;  
private Paint paint;  
private int ScreenW, ScreenH;  
public MySurfaceView(Context context) {  
super(context);  
th = new Thread(this);  
sfh = this.getHolder();  
sfh.addCallback(this); // 備注1  
paint = new Paint();  
paint.setAntiAlias(true);  
paint.setColor(Color.RED);  
this.setKeepScreenOn(true);// 保持屏幕常亮  
}  
@Override  
public void startAnimation(Animation animation) {  
super.startAnimation(animation);  
}  
public void surfaceCreated(SurfaceHolder holder) {  
ScreenW = this.getWidth();// 備注2  
ScreenH = this.getHeight();  
th.start();  
}  
private void draw() {  
try {  
canvas = sfh.lockCanvas(); // 得到一個canvas實例  
canvas.drawColor(Color.WHITE);// 刷屏  
canvas.drawText("Himi", 100, 100, paint);// 畫文字文本  
canvas.drawText("這就是簡單的一個游戲框架", 100, 130, paint);  
sfh.unlockCanvasAndPost(canvas); // 將畫好的畫布提交  
} catch (Exception ex) {  
} finally { // 備注3  
if (canvas != null)  
sfh.unlockCanvasAndPost(canvas);  
}  
}  
public void run() {  
while (true) {  
draw();  
try {  
Thread.sleep(100);  
} catch (InterruptedException e) {  
// TODO Auto-generated catch block  
e.printStackTrace();  
}  
}  
}  
public void surfaceChanged(SurfaceHolder holder, int format, int width,  
int height) {  
}  
public void surfaceDestroyed(SurfaceHolder holder) {  
// TODO Auto-generated method stub  
}  
}  

 


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved