Introduction to 2D drawing in Android with example



Android comes along with powerful open-source API libraries which support custom 2D and 3D graphics as well animations. In this tutorial let’s concentrate only on 2D graphics.
               Android framework API provides 2D drawing APIs for simple animation that does not require major dynamic changes. There are two ways of implementation using these API.
  •    Drawing to a View
  •  Drawing on a Canvas

Drawing a circle to  View
                Drawing to view is a better option when your UI does not require dynamic changes in the application. The most convenient aspect of doing so is that the Android framework will provide you with a pre-defined Canvas to which you will place your drawing calls.
               This can be achieved simply by extending the View class and define an onDraw() callback method. Inside your View component's onDraw(), use the Canvas given to you for all your drawing, using various Canvas.draw...() methods (Ex: canvas.drawCircle(x / 2, y / 2, radius, paint);). onDraw() is a callback method invoked when the view is initially drawn.

Below is a simple example code to draw a circle as described above

MainActivity.java

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(new MyView(this));
     }

     public class MyView extends View {
         public MyView(Context context) {
              super(context);
              // TODO Auto-generated constructor stub
         }

         @Override
         protected void onDraw(Canvas canvas) {
            // TODO Auto-generated method stub
            super.onDraw(canvas);
            int x = getWidth();
            int y = getHeight();
            int radius;
            radius = 100;
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.WHITE);
            canvas.drawPaint(paint);
            // Use Color.parseColor to define HTML colors
            paint.setColor(Color.parseColor("#CD5C5C"));
            canvas.drawCircle(x / 2, y / 2, radius, paint);
        }
     }
}





Drawing rectangle on a canvas

             To draw dynamic 2D graphics where in your application needs to regularly re draw itself, drawing on a canvas is a better option. A Canvas works for you as an interface, to the actual surface upon which your graphics will be drawn.
If you need to create a new Canvas, then you must define the bitmap upon which drawing will actually be performed. The Bitmap is always required for a Canvas.
The below example explains to draw a rectangle as explained.


Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/rect">
</LinearLayout>

MainActivity.java

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Paint paint = new Paint();
        paint.setColor(Color.parseColor("#CD5C5C"));
        Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bg); 
        canvas.drawRect(50, 50, 200, 200, paint); 
        LinearLayout ll = (LinearLayout) findViewById(R.id.rect);
        ll.setBackgroundDrawable(new BitmapDrawable(bg));   
     }
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}


Source code of this application
Drawing a circle to View
Drawing rectangle on a canvas





Reactions:

11 comments :

  1. ll.setBackgroundDrawable(new BitmapDrawable(bg)); is depreciated
    can you tell me the better implementation for sdk19?

    ReplyDelete
    Replies
    1. It is deprecated indeed but should still be used for versions prior to jelly bean, so you could implement it something like this:

      int sdk = android.os.Build.VERSION.SDK_INT;
      if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
      setBackgroundDrawable(new BitmapDrawable(bg))
      } else {
      setBackground(new BitmapDrawable(bg));
      }

      Delete
    2. The constructor BitmapDrawable(Bitmap) is deprecated as well, not just the setBackgroundDrawable making both sections of code marked as deprecated. Is there another option to BitmapDrawable?

      Delete
    3. Hi, this constructor is the only one you should use:
      BitmapDrawable(Resources, Bitmap)
      Obtain resources by context.getResources().

      Source: http://developer.android.com/reference/android/graphics/drawable/BitmapDrawable.html#BitmapDrawable(android.content.res.Resources, android.graphics.Bitmap)

      Android reference is a great source of information in these situations.

      Delete
    4. This worked for me:

      ll.setBackground(new BitmapDrawable(getResources(), bg));

      Delete
  2. Great article, hard to find such clearness. thank you

    ReplyDelete
  3. Hi,

    If I need to draw a line of length exactly equal to 10mm on the screen how can I do that? How can we make sure that the length is 10mm on all mobile/tablet devices with various physical size and resolution?

    -Rushikesh.

    ReplyDelete
  4. What's different between drawing on a view and canvas? Since view itself also give you a canvas to draw too. Any explanation?

    ReplyDelete
  5. Simple and works
    Very helpful, thanks!

    ReplyDelete