Kosheen

SurfaceView Test 3 #16

May 16th, 2021
789
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class TestSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
  2.  
  3.     private DrawThread drawThread;
  4.  
  5.     public TestSurfaceView(Context context) {
  6.         super(context);
  7.         getHolder().addCallback(this);
  8.     }
  9.  
  10.     @Override
  11.     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
  12.     }
  13.  
  14.     @Override
  15.     public void surfaceCreated(SurfaceHolder holder) {
  16.         drawThread = new DrawThread(getContext(), getHolder());
  17.         drawThread.start();
  18.     }
  19.  
  20.     @Override
  21.     public void surfaceDestroyed(SurfaceHolder holder) {
  22.         drawThread.requestStop();
  23.         boolean retry =  true;
  24.         while(retry){
  25.             try{
  26.                 drawThread.join();
  27.                 retry = false;
  28.             } catch (InterruptedException e) {
  29.                 e.printStackTrace();
  30.             }
  31.         }
  32.  
  33.     }
  34.  
  35.     @Override
  36.     public boolean onTouchEvent(MotionEvent event) {
  37.         drawThread.set(event.getX(), event.getY(), 0);
  38.         return super.onTouchEvent(event);
  39.     }
  40. }
  41.  
  42. class DrawThread extends Thread{
  43.  
  44.     private SurfaceHolder surfaceHolder;
  45.     float x = -100000, y = -100000, radius = 0;
  46.     private volatile boolean running = true;
  47.  
  48.     public void set(float x, float y, float radius){
  49.         this.x = x;
  50.         this.y = y;
  51.         this.radius = radius;
  52.     }
  53.  
  54.     public DrawThread(Context context, SurfaceHolder surfaceHolder){
  55.         this.surfaceHolder = surfaceHolder;
  56.     }
  57.  
  58.     public void requestStop() {
  59.         running = false;
  60.     }
  61.  
  62.  
  63.  
  64.     @Override
  65.     public void run() {
  66.         Paint paint = new Paint();
  67.         paint.setColor(Color.YELLOW);
  68.         while (running){
  69.             Canvas canvas = surfaceHolder.lockCanvas();
  70.             if(canvas != null){
  71.                 try {
  72.                     canvas.drawColor(Color.BLUE);
  73.                     canvas.drawCircle(x,y,radius,paint);
  74.                 }
  75.                 finally {
  76.                     surfaceHolder.unlockCanvasAndPost(canvas);
  77.                 }
  78.             }
  79.             radius += 5;
  80.             try {
  81.                 Thread.sleep(1000);
  82.             } catch (InterruptedException e) {
  83.                 e.printStackTrace();
  84.             }
  85.         }
  86.     }
  87. }
RAW Paste Data