Home > Blockchain >  Android resize image to fit imageview
Android resize image to fit imageview

Time:01-24

I get an image from file chooser and I put it into imageview. I want the image to be fully visible even if it is larger than the image view. At the moment, it looks like below. The image is cropped on all sides

enter image description here

Here is xml of imageview

<FrameLayout
            android:id="@ id/fl_book_image"
            android:layout_width="match_parent"
            android:layout_height="@dimen/add_book_header_image_height"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <ImageView
                android:id="@ id/iv_book_image"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/colorImageViewBackground"
                android:contentDescription="@string/content_description"
                android:scaleType="centerCrop"
                android:adjustViewBounds="true"/>

            <ImageView
                android:id="@ id/iv_add_update_book"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end|bottom"
                android:contentDescription="@string/content_description"
                android:foreground="?attr/selectableItemBackgroundBorderless"
                android:padding="@dimen/add_update_book_icon_padding"
                android:src="@drawable/ic_vector_add_photo" />
</FrameLayout>

First ImageView is the one that contains cover, second one is that little edit pen in right bottom corner

CodePudding user response:

use android:scaleType="fitxy" You can find more information here: https://developer.android.com/reference/android/widget/ImageView.ScaleType.html

CodePudding user response:

I think you want CENTER_INSIDE or FIT_CENTER, which both maintain the aspect ratio but scale it down so it fits within the view bounds. FIT_CENTER will also scale up if the image is smaller than the view. If FIT_XY didn't change anything, I'm guessing you're setting the image source in code - you'll probably need to invalidate() the ImageView so it can recalculate its sizes and redraw.

But like @Tenfour04 says, a library like Glide will take care of a lot of this for you, and it'll be safer and more performant if you're potentially dealing with large images - e.g. if they're user-provided, or you're using high-res images so they look good on higher-end devices, but also want to support low-end devices that would struggle with large bitmaps.

You can handle that yourself - here's the docs on it, but they recommend using a library like Glide themselves!

  •  Tags:  
  • Related