How to scale a bitmap as per device width and height

public Bitmap scaleToActualAspectRatio(Bitmap bitmap) {
 if (bitmap != null) {
 boolean flag = true;

int deviceWidth = getWindowManager().getDefaultDisplay()
 .getWidth();
 int deviceHeight = getWindowManager().getDefaultDisplay()
 .getHeight();

int bitmapHeight = bitmap.getHeight(); // 563
 int bitmapWidth = bitmap.getWidth(); // 900

// aSCPECT rATIO IS Always WIDTH x HEIGHT rEMEMMBER 1024 x 768

if (bitmapWidth > deviceWidth) {
 flag = false;

// scale According to WIDTH
 int scaledWidth = deviceWidth;
 int scaledHeight = (scaledWidth * bitmapHeight) / bitmapWidth;

try {
 if (scaledHeight > deviceHeight)
 scaledHeight = deviceHeight;

bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
 scaledHeight, true);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }

if (flag) {
 if (bitmapHeight > deviceHeight) {
 // scale According to HEIGHT
 int scaledHeight = deviceHeight;
 int scaledWidth = (scaledHeight * bitmapWidth)
 / bitmapHeight;

try {
 if (scaledWidth > deviceWidth)
 scaledWidth = deviceWidth;

bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
 scaledHeight, true);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 }
 }
 return bitmap;
 }

Advertisements

About krishjlk

http://www.facebook.com/krishna.kanth.121

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: