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

September 5, 2012 | Rishabh Agrawal | General

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.set_image_id);

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*/

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

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);
}

This code will help you scale image for all screen sizes.


THE AUTHORRishabh Agrawal

Rishabh Agrawal is the founder of Creatiosoft, a company focused on creating high-quality software for the iGaming industry, specialising in poker and card games. With years of experience, Rishabh is dedicated to delivering engaging and user-friendly gaming experiences. Through this blog, he shares his passion and insights to help readers understand the latest trends and advancements in iGaming.

Recent Posts

The Future of Mobile Gaming: What to Expect in the Next 5 Years

Over the years, mobile gaming has seen amazing development and innovation utilized by the game development company in India. It…
06 Jun 2023 Rishabh Agrawal

How Do I Get Started With NFT Gaming?

The popularity of the NFT game has created a different fan base. There was a time when games were a…
18 Jul 2022 Rishabh Agrawal

What Are The Top Trends in NFT Marketplace 2022?

The NFTs are the new engaging and revolutionary technology across the globe. Though, these non-fungible tokens appeared for the first…
09 Jun 2022 Rishabh Agrawal