Android游戏编程之SurfaceView进行连续渲染(2)

下面看一个实例,其中使用SurfaceHolder在一个单独线程中执行渲染。

package org.example.ch04_Android_basics;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;

public class SurfaceViewTest extends Activity {
 FastRenderView renderView;

@Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
  renderView = new FastRenderView(this);
  setContentView(renderView);
 }

@Override
 protected void onPause() {
  // TODO Auto-generated method stub
  super.onPause();
  renderView.pause();
 }

@Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  renderView.resume();
 }
 
 class FastRenderView extends SurfaceView implements Runnable{
  Thread renderThread = null;
  SurfaceHolder holder;
  Random rand = new Random();
  volatile boolean running = false;
 
  public FastRenderView(Context context) {
   super(context);
   // TODO Auto-generated constructor stub
   holder = getHolder();
  }
 
  public void resume(){
   running = true;
   renderThread = new Thread(this);
   renderThread.start();
  }
 
  public void run(){
   while(running){
    if(!holder.getSurface().isValid())
     continue;
   
    Canvas canvas = holder.lockCanvas();
    canvas.drawRGB(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
    holder.unlockCanvasAndPost(canvas);
   }
  }
 
  public void pause(){
   running = false;
   while(true){
    try{
     renderThread.join();
     break;
    }catch(InterruptedException e){
     // retry
    }
   }
  }
 }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/33f31474500665d2d2306b3009897db5.html