Scaling images in a way that suits all screen sizes in android

It is not a good coding practice to scale a image by specifying its height and width in pixels because on different screen sizes i.e HDPI,LDPI,MDPI etc .Hence ,it is recommended to scale a image  according to the screen dimensions in the following way.

 The following function is used for scaling bitmap which is a part of  android.graphics.Bitmap

Bitmap.createScaledBitmap(Bitmap_image, width, height,true);

 STEPS:

1.Create a image view object and associate it with its corresponding ImageView in xml file.


ImageView _imgBitmap;

_imgBitmap = (ImageView) findViewById(R.id.<i>set_image_id</i>);

2.Get the screen dimensions in the following way and use them to scale the bitmap.


//code for scaling bitmap using screen dimensions to suit all  screen sizes

&nbsp;

// DisplayMetrics A structure describing general information about a display, such as its //size, density, and font scaling.

&nbsp;

DisplayMetrics displaymetrics = new DisplayMetrics();

//getting display data

getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

int height = displaymetrics.heightPixels;//screen height in pixels

int width = displaymetrics.widthPixels;//screen width in pixels

float w= (float) (width/(3.5));//scaling w.r.t screen dimensions

float h= (float)(height/(4.4));

int w1=(int)w;//casting float values to int as the createScaledBitmap takes int args

int h1=(int)h;

Bitmap scaledBmap = Bitmap.createScaledBitmap(PlayMenuActivity.photo, w1, h1,true);

//displaying captured pic

if (PlayMenuActivity.photo != null) {

_imgBitmap.setImageBitmap(scaledBmap);

}

&nbsp;
Advertisements

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