How to scale an Image in ImageView to keep the aspect ratio

前端 未结 25 1841
孤独总比滥情好
孤独总比滥情好 2020-11-22 04:59

In Android, I defined an ImageView\'s layout_width to be fill_parent (which takes up the full width of the phone).

If the imag

相关标签:
25条回答
  • 2020-11-22 05:20

    I have an algorithm to scale a bitmap to bestFit the container dimensions, maintaining its aspect ratio. Please find my solution here

    Hope this helps someone down the lane!

    0 讨论(0)
  • 2020-11-22 05:20

    You can scale image that will also reduce the size of your image. There is a library for it you can download and use it. https://github.com/niraj124124/Images-Files-scale-and-compress.git

    How to use 1)Import the compressor-v1.0. jar to your project. 2)Add the below sample code to test. ResizeLimiter resize = ImageResizer.build(); resize.scale("inputImagePath", "outputImagePath",imageWidth, imageHeight); Many more methods are there according to your requirement

    0 讨论(0)
  • 2020-11-22 05:23

    If you want an ImageView that both scales up and down while keeping the proper aspect ratio, add this to your XML:

    android:adjustViewBounds="true"
    android:scaleType="fitCenter"
    

    Add this to your code:

    // We need to adjust the height if the width of the bitmap is
    // smaller than the view width, otherwise the image will be boxed.
    final double viewWidthToBitmapWidthRatio = (double)image.getWidth() / (double)bitmap.getWidth();
    image.getLayoutParams().height = (int) (bitmap.getHeight() * viewWidthToBitmapWidthRatio);
    

    It took me a while to get this working, but this appears to work in the cases both where the image is smaller than the screen width and larger than the screen width, and it does not box the image.

    0 讨论(0)
  • 2020-11-22 05:24

    When doing this programmatically, be sure to call the setters in the correct order:

    imageView.setAdjustViewBounds(true)
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP)
    
    0 讨论(0)
  • 2020-11-22 05:25

    If you want your image occupy the maximum possible space then the best option would be

    android:layout_weight="1"
    android:scaleType="fitCenter"
    
    0 讨论(0)
  • 2020-11-22 05:26

    Take a look at ImageView.ScaleType to control and understand the way resizing happens in an ImageView. When the image is resized (while maintaining its aspect ratio), chances are that either the image's height or width becomes smaller than ImageView's dimensions.

    0 讨论(0)
提交回复
热议问题