Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImageView bitmap scale dimensions

I have a Bitmap that is larger than the ImageView that I'm putting it in. I have the ScaleType set to center_inside. How do I get the dimensions of the scaled down image?

like image 672
Jay Avatar asked Apr 07 '26 07:04

Jay


1 Answers

Ok. I probably should have been clearer. I needed the height and width of the scaled Bitmap before it's ever drawn to the screen so that I could draw some overlays in the correct position. I knew the position of the overlays in the original Bitmap but not the scaled. I figured out some simple formulas to calculate where they should go on the scaled Bitmap.

I'll explain what I did in case someone else may one day need this.

I got the original width and height of the Bitmap. The ImageView's height and width are hard-coded in the xml file at 335.

int bitmap_width = bmp.getWidth();
int bitmap_height = bmp.getHeight();

I determined which one was larger so that I could correctly figure out which one to base the calculations off of. For my current example, width is larger. Since the width was scaled down to the the width of the ImageView, I have to find the scaled down height. I just multiplied the ratio of the ImageView's width to the Bitmap's width times the Bitmap's height. Division is done last because Integer division first would have resulted in an answer of 0.

int scaled_height = image_view_width * bitmap_height / bitmap_width;

With the scaled height I can determine the amount of blank space on either side of the scaled Bitmap by using:

int blank_space_buffer = (image_view_height - scaled_height) / 2;

To determine the x and y coordinates of where the overlay should go on the scaled Bitmap I have to use the original coordinates and these calculated numbers. The x coordinate in this example is easy. Since the scaled width is the width of the ImageView, I just have to multiply the ratio of the ImageView's width to the Bitmap's width with the original x coordinate.

int new_x_coord = image_view_width * start_x / bitmap_width;

The y coordinate is a bit trickier. Take the ratio of the Bitmap's scaled height to the Bitmap's original height. Multiply that value with the original y coordinate. Then add the blank area buffer.

int new_y_coord = scaled_height * start_y / bitmap_height + blank_space_buffer;

This works for what I need. If the height is greater than the width, just reverse the width and height variables.

like image 172
Jay Avatar answered Apr 08 '26 19:04

Jay



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!