Wednesday, May 12, 2010

Draw a bitmap on View

It's a simple example to draw a bitmap on screen in View. The content view is set to a View, and the drawing is achieved in onDraw method.

Draw a bitmap on View

To make it simple, a bitmap of 320x480 (the size of HVGA) was prepared. It's in /res/drawable/ folder, and will be loaded using the following codes:

Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.googlelogo320x480);

canvas.drawBitmap(myBitmap, 0, 0, null);

package com.exercise.AndroidPaint;

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

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

private 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
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.googlelogo320x480);
canvas.drawBitmap(myBitmap, 0, 0, null);
}
}
}


Download the files.

Next: Draw something on a Canvas.

3 comments:

cinci-hal said...

I am an absolute beginner to android development and java and am trying to wrap my head around what is happening in this tutorial. It looks like the java class overrides the xml. Is this correct? I was wondering how it would be different if the xml Layout already had say buttons, text, and such, and you wanted to keep those, but add the view that you created in this tutorial them.

Erik said...

hello cinci-hal,

Is it what you means? Include custom view in XML,

cinci-hal said...

That answered my question exactly. Great Tutorials, by the way!