自从大二写了个android游戏去参加比赛,之后就一直写应用,一直没用过SurfaceView了,现在进入了游戏公司,准备从基础开始重新快速的学一下这个,然后再去研究openGL和游戏引擎。
直接上代码吧:
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.view.SurfaceHolder;
import android.view.animation.Animation; public class MySurfaceView extends SurfaceView implements Callback, Runnable { private SurfaceHolder sfh;
private Thread th;
private Canvas canvas;
private Paint paint;
private boolean threadFlag; public MySurfaceView(Context context) {
// this(context, null); super(context);
sfh = this.getHolder();
sfh.addCallback(this);
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.RED);
paint.setTextSize(20);
Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
paint.setTypeface(font);
this.setKeepScreenOn(true);
} public MySurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
// th = new Thread(this);
// sfh = this.getHolder();
// sfh.addCallback(this);
// paint = new Paint();
// paint.setAntiAlias(true);
// paint.setColor(Color.RED);
// this.setKeepScreenOn(true);
} public void startAnimation(Animation animation) {
super.startAnimation(animation);
} public void surfaceCreated(SurfaceHolder holder) {
threadFlag = true;
th = new Thread(this);
th.start();
} private void draw() {
try {
canvas = sfh.lockCanvas(); // 获取画布
if (canvas != null) {
canvas.drawColor(Color.WHITE);// 画布颜色
canvas.drawText("奋斗的小猿", 100, 100, paint);
canvas.drawText("加班,还是不加班,it's a question!", 100, 130, paint);
}
} catch (Exception ex) {
} finally {
if (canvas != null)
sfh.unlockCanvasAndPost(canvas);
}
} public void run() {
while (threadFlag) {
Log.i("ceshi", "threadFlag=true");
draw();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
} public void surfaceDestroyed(SurfaceHolder holder) {
threadFlag = false;
} }
这里Activity用的是
setContentView(new MySurfaceView(getApplicationContext()));
如果想在布局中引用:
<com.tq.listviewtest.MySurfaceView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible" >
</com.tq.listviewtest.MySurfaceView>
setContentView(R.layout.activity_main);
则构造方法应改为:
public MySurfaceView(Context context) {
this(context, null);
} public MySurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
sfh = this.getHolder();
sfh.addCallback(this);
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.RED);
paint.setTextSize(20);
Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
paint.setTypeface(font);
this.setKeepScreenOn(true);
}
因为android 加载布局时,只是去执行了第二个构造方法,第一个构造方法没有执行,所以我们要把初始化写在第二个构造方法中了。