Bitmap Transformations

Bitmap Transformations (Scaling, Rotation)

Note : uncomment the code to see various effects.

/res/layout/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">
	<TextView android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="@string/hello" />
</LinearLayout>

/res/drawable/test.bmp

Activity file

package com.androidwork.bmpdemo;

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

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

	}
}

class loadbitmap extends View {

	public loadbitmap(Context context) { 
		super(context);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onDraw(Canvas canvas) {

		Bitmap pic = BitmapFactory.decodeResource(getResources(),
				R.drawable.test);
		// for scaling down ///1

		// Bitmap sm = Bitmap.createScaledBitmap(pic, 50, 100, false);
		// ////////////////////////

		// //transforming bmp ////
		// Matrix mirrorMatrix = new Matrix();
		// //mirrorMatrix.preScale(-1, -1);
		// //mirrorMatrix.preScale(1, -1);
		// mirrorMatrix.preScale(2, -1);
		// //mirrorMatrix.preScale(1, -2);

		// Bitmap mirrorPic = Bitmap.createBitmap(pic, 0, 0,
		// pic.getWidth(), pic.getHeight(), mirrorMatrix, false);
		// /////////////////

		// /////30 degree rotation ////////////

		Matrix mirrorAndTilt30 = new Matrix();

		mirrorAndTilt30.preRotate(180);
		// mirrorAndTilt30.preScale(-1, 1);
		Bitmap mirrorPic = Bitmap.createBitmap(pic, 0, 0, pic.getWidth(),
				pic.getHeight(), mirrorAndTilt30, false);
		// ////////////////////////

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

	}

}

Output