Example of Surface View
public class GameView extends SurfaceView
{
private SurfaceHolder surfaceHolder;
public GameView(Context context) {
init();
}
private void init() {
surfaceHolder = getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
surfaceHolder = holder;
mTask = new MySurfaceViewThread(holder);
mTask.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
Log.w("surfaceChanged", "Running.......");
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
mTask.postStop();
}
});
}
public void draw(Canvas c) {
//Draw Something
}
public class MySurfaceViewThread extends Thread {
private SurfaceHolder holder = null;
private volatile boolean run = true;
Canvas c;
public MySurfaceViewThread(SurfaceHolder h) {
holder = h;
}
@Override
public void run() {
while (run) {
try {
if (holder.getSurface().isValid()) {
c = holder.lockCanvas();
draw(c);
}
holder.unlockCanvasAndPost(c);
}
}
}
public void postStop() {
run = false;
}
}
}
public class GameView extends SurfaceView
{
private SurfaceHolder surfaceHolder;
public GameView(Context context) {
init();
}
private void init() {
surfaceHolder = getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
surfaceHolder = holder;
mTask = new MySurfaceViewThread(holder);
mTask.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
Log.w("surfaceChanged", "Running.......");
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
mTask.postStop();
}
});
}
public void draw(Canvas c) {
//Draw Something
}
public class MySurfaceViewThread extends Thread {
private SurfaceHolder holder = null;
private volatile boolean run = true;
Canvas c;
public MySurfaceViewThread(SurfaceHolder h) {
holder = h;
}
@Override
public void run() {
while (run) {
try {
if (holder.getSurface().isValid()) {
c = holder.lockCanvas();
draw(c);
}
holder.unlockCanvasAndPost(c);
}
}
}
public void postStop() {
run = false;
}
}
}
No comments:
Post a Comment