Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale image relative to the screen size?

i am making an android app in which i scale the bitmap using bitmap2 = Bitmap.createScaledBitmap(bmp, 150, 150, true);

this image looks good enough on a mobile with big screen ...but it goes out of proportion when used on a phone with small size .....any one knows the solution for it?

like image 301
Ankit Srivastava Avatar asked Dec 04 '25 03:12

Ankit Srivastava


2 Answers

You need to specify the image size in dp, just like you do in XML. To do the conversion from dp to pixels you can use something like:

float ht_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ht, getResources().getDisplayMetrics());
float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, wt, getResources().getDisplayMetrics());

For your particular case use:

float ht_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, getResources().getDisplayMetrics());
float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, getResources().getDisplayMetrics());

and scale the bitmap with ht_px and wt_px. You might need to change 150 to 75.

like image 71
Heinrisch Avatar answered Dec 06 '25 17:12

Heinrisch


take height and width of screen and calculate your size

DisplayMetrics display = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(display);
    int screenWidth = display.widthPixels;
    int  screenHeight = display.heightPixels; 

like you want to show your bitmap half of the screen then-

 bitmap2 = Bitmap.createScaledBitmap(bmp, screenWidth/2, screenHeight/2, true);

calculate it according to you requirement.

like image 25
T_V Avatar answered Dec 06 '25 16:12

T_V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!