Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing ImageView to fit to aspect ratio

I need to resize an ImageView such that it fits to the screen, maintains the same aspect ratio. The following conditions hold:

  • Images are a fixed width (size of the width of screen)
  • Images are downloaded from the Internet, i.e. size can only be determined later
  • Aspect ratio for each image will vary; some are tall, some are square, some are flat
  • ImageView's height needs to change, either bigger or smaller based on the aspect ratio of the
  • Excess height is cropped, can't have a lot of empty space like it is by default.

For example, a tiny 50x50 image on a 400 px width screen would scale the image up to 400x400 px. A 800x200 image would scale to 400x100.

I've looked at most of the other threads, and many proposed solutions like simply changing adjustViewBounds and scaleType will only scale down an image, and not scale it up.

like image 929
Muz Avatar asked Sep 13 '12 05:09

Muz


People also ask

What is a 2 3 aspect ratio?

2:3 Aspect Ratio. 2:3 is the most popular aspect ratio for printing. Print sizes that are a 2:3 aspect ratio and are popular with poster, canvas, and decal printing are 24 x 36 inches and 40 x 60 inches.


1 Answers

ImageView mImageView; // This is the ImageView to change

// Use this in onWindowFocusChanged so that the ImageView is fully loaded, or the dimensions will end up 0.
public void onWindowFocusChanged(boolean hasFocus) 
{
    super.onWindowFocusChanged(hasFocus);

    // Abstracting out the process where you get the image from the internet
    Bitmap loadedImage = getImageFromInternet (url);

    // Gets the width you want it to be
    intendedWidth = mImageView.getWidth();

    // Gets the downloaded image dimensions
    int originalWidth = loadedImage.getWidth();
    int originalHeight = loadedImage.getHeight();

    // Calculates the new dimensions
    float scale = (float) intendedWidth / originalWidth;
    int newHeight = (int) Math.round(originalHeight * scale);

    // Resizes mImageView. Change "FrameLayout" to whatever layout mImageView is located in.
    mImageView.setLayoutParams(new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT));
    mImageView.getLayoutParams().width = intendedWidth;
    mImageView.getLayoutParams().height = newHeight;
}
like image 66
Muz Avatar answered Oct 22 '22 06:10

Muz