Sunday, July 11, 2010

Andriod 2D Graphics - Drawing Pad Sample

In this aritcle shows how to use onDraw() method and create a simple drawing program. The only significant files are Draw activity and the DrawView. You should see a black screen and be able to draw on it with your finger.

This activity creates the DrawView and sets it as activity's main content. It also sets the borderless window.

MainActivity.java
public class MainActivity extends Activity {
    DrawView drawView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        drawView = new DrawView(this);
        setContentView(drawView);
        drawView.requestFocus();
    }

    // DrawView is a view. It listens to mouse click events and draws a point at the point that it was clicked on.
   public class DrawView extends View implements OnTouchListener {
        List<Point> points = new ArrayList<Point>();
        Paint paint = new Paint();
        public DrawView(Context context) {
        super(context);
        setFocusable(true);
        setFocusableInTouchMode(true);
        this.setOnTouchListener(this);
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);
        }

    @Override
    public void onDraw(Canvas canvas) {
        for (Point point : points) {
            canvas.drawCircle(point.x, point.y, 5, paint);
        }
    }

    public boolean onTouch(View view, MotionEvent event) {
        Point point = new Point();
        point.x = event.getX();
        point.y = event.getY();
        points.add(point);
        invalidate();
        return true;
    }
}
    class Point {
        float x, y;
        @Override
        public String toString() {
        return x + ", " + y;
        }
    }
}

No comments:

Post a Comment