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

前端 未结 25 1823
孤独总比滥情好
孤独总比滥情好 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: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.

提交回复
热议问题