Wednesday 12 May 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.

No comments:

Post a Comment