Dec 12, 2011

Scale Bitmap

To scale bitmap, we can use the following code:
Matrix matrix = new Matrix();
matrix.postScale(xScale, yScale);
Bitmap newBitmap = Bitmap.createBitmap(oldBitmap, 0, 0, orgWidth, orgHeight, matrix, true);


example:

Scale Bitmap

package com.AndroidScaleBitmap;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.widget.ImageView;

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

ImageView image1 = (ImageView)findViewById(R.id.image1);
ImageView image2 = (ImageView)findViewById(R.id.image2);

Bitmap oldBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

int orgWidth = oldBitmap.getWidth();
int orgHeight = oldBitmap.getHeight();
int newWidth = 300;
int newHeight = 300;
float xScale = newWidth/orgWidth;
float yScale = newHeight/orgHeight;

Matrix matrix = new Matrix();
matrix.postScale(xScale, yScale);
Bitmap newBitmap = Bitmap.createBitmap(oldBitmap, 0, 0, orgWidth, orgHeight, matrix, true);

image1.setImageBitmap(oldBitmap);
image2.setImageBitmap(newBitmap);
}
}


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

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/image2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>




No comments:

Post a Comment

Infolinks In Text Ads