Using Bitmap Class Object To Draw An Image

This is a sample program to draw an image using Bitmap class object.

Underlying Algorithm:

Basic description of algorithm in step by step form:

1.) Create a Project DrawBitmap.
2.) To draw an image we will create a inner class BitmapView which will extends View :

 

class BitmapView extends View
{
public BitmapView(Context context) {
super(context);
}
@Override
public void onDraw(Canvas canvas) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.five);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bmp, 10, 10, null);
}
}

 

 

3.) Put an image in res/drawable
4.) Run the application.

Steps to Create:

1.) Open Eclipse. Use the New Project Wizard and select Android Project Give the respective project name i.e. DrawBitmap. Enter following information:
Project name: DrawBitmap
Build Target: Android 2.3
Application name: DrawBitmap
Package name: com.sample.DrawBitmap
Create Activity: DrawBitmap

On Clicking Finish DrawBitmap code structure is generated with the necessary Android Packages being imported along with DrawBitmap.java. DrawBitmap class will look like following:

 

package com.sample.DrawBitmap;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;

public class DrawBitmap extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new BitmapView(this));
}

class BitmapView extends View {
public BitmapView(Context context) {
super(context);
}

@Override
public void onDraw(Canvas canvas) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.five);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bmp, 10, 10, null);
}
}
}

 

 

Output โ€“The final output:

Leave a Comment:

5 comments
Jason says May 17, 2011

Thanks so much for this tutorial. I’m very much a noob and am piecing my app together. I wasted several hours over this past weekend trying to find a clear basic tutorial explaining displaying a bitmap. Thanks again

Reply
Jason says May 17, 2011

Thanks so much for this tutorial. I’m very much a noob and am piecing my app together. I wasted several hours over this past weekend trying to find a clear basic tutorial explaining displaying a bitmap. Thanks again

Reply
Shalini says August 19, 2011

Its nice.

Reply
alnie jacobe says December 5, 2011

guys,can anyone help me to create an application that allows user to draw ther signature using canvas?

Reply
Stephanie says March 6, 2013

Thanks!! Nice and simple tutorial. Exactly what I’m looking for ๐Ÿ™‚

Reply
Add Your Reply