Dec 6, 2012

Draw path on SurfaceView's canvas

Example to detect touch events and draw path on SurfaceView's canvas accordingly.

Draw path on SurfaceView's canvas


package com.TestSurefaceView;

import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

 public class MainActivity extends Activity {
  
  MySurfaceView mySurfaceView;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   mySurfaceView = new MySurfaceView(this);
   setContentView(mySurfaceView); 
  }
  
  class MySurfaceView extends SurfaceView{

   Path path;
   
   Thread thread = null;
   SurfaceHolder surfaceHolder;
   volatile boolean running = false;
   
   private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
   Random random;
   
   public MySurfaceView(Context context) {
    super(context);
    surfaceHolder = getHolder();
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(3);
    paint.setColor(Color.WHITE);
   }

   @Override
   public boolean onTouchEvent(MotionEvent event) {
    if(event.getAction() == MotionEvent.ACTION_DOWN){
     path = new Path();
     path.moveTo(event.getX(), event.getY());
    }else if(event.getAction() == MotionEvent.ACTION_MOVE){
     path.lineTo(event.getX(), event.getY());
    }else if(event.getAction() == MotionEvent.ACTION_UP){
     path.lineTo(event.getX(), event.getY());
    }
    
    if(path != null){
     Canvas canvas = surfaceHolder.lockCanvas();
     canvas.drawPath(path, paint);
     surfaceHolder.unlockCanvasAndPost(canvas);
    }

    return true; 
   }
  }
}



Related Post:
- Detect multi-touch, on SurfaceView

2 comments:

  1. it's Very nice for me, but i have problem in undo redo, i could not find the right solution for it. so please tell me how to perform undo redo in this example using command pattern.
    And send me a sample on my e-mail- hemant.katariya26@gmail.com

    ReplyDelete

Infolinks In Text Ads