Resizing ImageView to fit to aspect ratio

后端 未结 3 1027
夕颜
夕颜 2020-11-30 06:20

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 o
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 06:42

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

提交回复
热议问题