2015년 9월 12일 토요일

SurfaceView Simple


SimpleSurfaceView.java
public class SimpleSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable {

 private SurfaceHolder holder;
 private Thread thread;
 
 private Bitmap image;
 private int px = 0;
 private int py = 0;
 private int vx = 1;
 private int vy = 1;
 
 public SimpleSurfaceView(Context context) {
  super(context);
  
  Resources r = getResources();
  image = BitmapFactory.decodeResource(r, R.drawable.ic_launcher);
  
  holder = getHolder();
  holder.addCallback(this);
  holder.setFixedSize(getWidth(), getHeight());
 }

 public void surfaceCreated(SurfaceHolder holder) {
  thread = new Thread(this);
  thread.start();
 }

 public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
  
 }
 
 public void surfaceDestroyed(SurfaceHolder holder) {
  thread = null;
 }
 
 public void stopThread() {
  thread = null;
 }
 
 @Override
 public void run() {
  Canvas canvas;
  while (thread != null) {
   canvas = holder.lockCanvas();
   canvas.drawColor(Color.WHITE);
   canvas.drawBitmap(image,  px-40,  py-40, null);
   holder.unlockCanvasAndPost(canvas);
   
   if (px < 0 || getWidth() < px ) vx = -vx;
   if (py < 0 || getHeight() < py ) vy = -vy;
   
   px += vx;
   py += vy;
  }
 }
}

SimpleSurfaceViewActivity.java
public class SimpleSurfaceViewActivity extends Activity {
 SimpleSurfaceView surfaceView;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  getWindow().setFormat(PixelFormat.TRANSLUCENT);
  
  surfaceView = new SimpleSurfaceView(this);
  setContentView(surfaceView);
 }
 
 public void onPause() {
  super.onPause();
  surfaceView.stopThread();
  
 }
}

댓글 없음:

댓글 쓰기