user2401745
user2401745

Reputation: 367

Android-Draw on SurfaceView

I am creating an app to draw free shapes on the surface screen but i could only draw separated points my problem is . i want the points to be connected to each other when i draw them not lifting my finger from the screen . i mean as long as i am touching the screen draw.here's my code so far.

   public class SurfaceViewActivity extends Activity  {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new DrawingView(this));
}

class DrawingView extends SurfaceView {

    private final SurfaceHolder surfaceHolder;
    private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private List<Point> pointsList = new ArrayList<Point>();

    public DrawingView(Context context) {
        super(context);
        surfaceHolder = getHolder();
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(3);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (surfaceHolder.getSurface().isValid()) {

                // Add current touch position to the list of points
                pointsList.add(new Point((int)event.getX(), (int)event.getY()));

                // Get canvas from surface
                Canvas canvas = surfaceHolder.lockCanvas();

                // Clear screen
                canvas.drawColor(Color.BLACK);

                // Iterate on the list
                for(int i=0; i<pointsList.size(); i++) {
                    Point current = pointsList.get(i);

                    // Draw points
                   canvas.drawPoint(current.x, current.y, paint);

                }

                // Release canvas
                surfaceHolder.unlockCanvasAndPost(canvas);
            }
        }
        return false;
    }
}

}

Upvotes: 1

Views: 1087

Answers (2)

Ali Imran
Ali Imran

Reputation: 9237

you can use this function to draw smooth lines

  public void drawBrzierLine(Canvas mCanvas, float xi, float yi, float xd, float yd) {

    Point start = new Point((int) xi, (int) yi);
    Point end = new Point((int) xd, (int) yd);
    Path mPath = new Path();
    mPath.reset();
    mPath.moveTo(start.x, start.y);
    mPath.quadTo(start.x, start.y, end.x, end.y);
    mCanvas.drawPath(mPath, mPaint);

}

Upvotes: 3

Prownage
Prownage

Reputation: 79

In onTouchEvent(MotionEvent event) you only handle ACTION_DOWN. So this code will only run when you press down on the screen. Use ACTION_MOVE instead. http://developer.android.com/reference/android/view/MotionEvent.html

Upvotes: 2

Related Questions