Beginner 2D Drawing In Android

This is a really basic, super dumbed down tutorial for 2D drawing in Android. If you’ve never done it before, this might help. If you’ve ever done it before… you already know this stuff.

And with that out of the way… start a new Android project and put the following into the onCreate method:

setContentView(new MyDrawableView(this));

Near as I can tell, if you want to do any graphics-type drawing in Android, you need to get some level of access to the onDraw method, which resides in the View class. But this means you need to create a new view class. So… create a new class and name it “MyDrawableView”. You should end up with something like this:

public class DrawableView extends View{
Context mContext;

public DrawableView(Context context) {
super
(context);
mContext = context;
}
}

Now, lets add an override for our onDraw method:

@Override

protected void onDraw(Canvas canvas){
Paint myPaint = new Paint();
myPaint.setStrokeWidth(3);
myPaint.setColor(0xFF097286);
canvas.drawCircle(200, 200, 50, myPaint);
canvas.drawBitmap(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.icon), 184, 184, null);
invalidate();
}

What we’ve done here is nothing more than draw a circle and place the application icon in it. The Canvas object holds all the drawing calls (read more about it here) and the draw objects are layered one on top of another in the order that they are called. The “invalidate” method at the end forces a draw on the canvas.

I would provide source code, but I really can’t do much more than recommend that you take a look at source code over at anddev.org for a similar tutorial. They also glance at some very simple procedural animation, so it is definately worth your time if you’re looking a little deeper into basic Android drawing.

7 Comments

  1. superjet:

    Hey thanks for this…

  2. De:

    Short and clear, thanks :)

  3. Frankkie:

    Thanks !
    Just what I was looking for :D

  4. cykan:

    Yo thanks! Will help alot!

  5. dianfar:

    thank, this is what i looking for

  6. ch1gz:

    I would remove the invalidate() statement at the bottom otherwise the view will continuously repaint itself

  7. hany:

    thanks , this is helpful to me

Leave a comment