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

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

    For anyone of you who wants the image to fit exact the imageview with proper scaling and no cropping use

    imageView.setScaleType(ScaleType.FIT_XY);
    

    where imageView is the view representing your ImageView

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 05:11

    See android:adjustViewBounds.

    Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.

    0 讨论(0)
  • This worked for me:

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxWidth="39dip"
    android:scaleType="centerCrop"
    android:adjustViewBounds ="true"
    
    0 讨论(0)
  • 2020-11-22 05:17

    Yo don't need any java code. You just have to :

    <ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop" />
    

    The key is in the match parent for width and height

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

    Quick answer:

    <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="center"
            android:src="@drawable/yourImage"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    0 讨论(0)
提交回复
热议问题