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

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

    You can calculate screen width. And you can scale bitmap.

     public static float getScreenWidth(Activity activity) {
            Display display = activity.getWindowManager().getDefaultDisplay();
            DisplayMetrics outMetrics = new DisplayMetrics();
            display.getMetrics(outMetrics);
            float pxWidth = outMetrics.widthPixels;
            return pxWidth;
        }
    

    calculate screen width and scaled image height by screen width.

    float screenWidth=getScreenWidth(act)
      float newHeight = screenWidth;
      if (bitmap.getWidth() != 0 && bitmap.getHeight() != 0) {
         newHeight = (screenWidth * bitmap.getHeight()) / bitmap.getWidth();
      }
    

    After you can scale bitmap.

    Bitmap scaledBitmap=Bitmap.createScaledBitmap(bitmap, (int) screenWidth, (int) newHeight, true);
    

提交回复
热议问题