Create a new class MyView extends View, MyView.java.
package com.AndroidMyCanvas; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class MyView extends View { boolean freeTouched = false; Path freePath; public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); } public MyView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); Paint paint = new Paint(); paint.setStyle(Paint.Style.STROKE); paint.setColor(Color.WHITE); paint.setStrokeWidth(3); if(freeTouched){ canvas.drawPath(freePath, paint); } } @Override public boolean onTouchEvent(MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_UP: freeTouched = false; break; case MotionEvent.ACTION_DOWN: freeTouched = true; freePath = new Path(); freePath.moveTo(event.getX(), event.getY()); break; case MotionEvent.ACTION_MOVE: freePath.lineTo(event.getX(), event.getY()); invalidate(); break; } return true; } }
Modify main Java activity to setContentView() using our custom View, MyView.
package com.AndroidMyCanvas; import android.app.Activity; import android.os.Bundle; public class AndroidMyCanvasActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new MyView(this)); } }
Next:
- Get the canvas bitmap of custom View