SurfaceView实例
SurfaceView实例
1、看着别人的实例,写了一个SurfaceView应用的实例,基本是照着别人代码敲了一遍,运行后如下图
2、代码如下,没有注释
package com.demo;
import java.util.Vector;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup.LayoutParams;
public class SurfaceViewDemoActivity extends Activity {
SurfaceHolder sh = null;
Vector<Float> vx = new Vector<Float>();
Vector<Float> vy = new Vector<Float>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SurView surView = new SurView(this);
setContentView(surView);
}
class SurView extends SurfaceView implements SurfaceHolder.Callback {
public SurView(Context context) {
super(context);
sh = getHolder();
sh.addCallback(this);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
new Thread(new SurLoop()).start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void doDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.GRAY);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
paint.setStyle(Style.STROKE);
for (int i = 0; i < vx.size(); i++) {
canvas.drawCircle(vx.elementAt(i), vy.elementAt(i), 10, paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
vx.add(event.getX());
vy.add(event.getY());
}
return true;
}
class SurLoop implements Runnable {
@Override
public void run() {
while (true) {
try {
Canvas canvas = sh.lockCanvas();
doDraw(canvas);
sh.unlockCanvasAndPost(canvas);
Thread.sleep(20);
} catch (Exception e) {
}
}
}
}
}
}