Mazen
Mazen

Reputation: 213

Android ImageView being cropped

first of all here's a graphic to illustrate my problem: Graphic

On the left image you can see how it should look. And this is also how AndroidStudio shows it in the preview. But if I run it on the emulator, it cropps the image and only the dark green part is left. (right image)

<ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/img_header"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:focusableInTouchMode="false"
        android:src="@drawable/header"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop" />

The parent view:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".menu">

I trief different scaleTypes, but nothing gives me the outcome I want to have. Not the first time I'm sturggling with ImageViews, but the first time I can't solve the issue myself...

If I remove the "adjustViewBounds" the preview shows the same outcome as the device/emulator. In case that that is a hint for someone.

Edit: I created a second version of the header, which is double the size. And now it works with "fitXy" and "adjustViewBound(true)". But why? The original image was 512px in height, which should've been enough for adjustViewBounds to keep the aspect ratio.

Upvotes: 1

Views: 2518

Answers (2)

kirkadev
kirkadev

Reputation: 348

Your problem may be because the ImageView is not yet fully initialized or sized when you try to set the image. The time it takes to load and render an image in the ViewHolder may vary, especially if the images are large or there are many of them.

Try load images using the Glide, which are good at asynchronous loading and image caching

        Glide.with(itemBinding.root)
            .load(imgUrl)
            .error(ColorDrawable(PLACEHOLDER_COLOR))
            .placeholder(ColorDrawable(PLACEHOLDER_COLOR))
            .into(itemBinding.image)

instead of ImageView.load() method

Upvotes: 0

erik
erik

Reputation: 4958

It sounds like you want CENTER_INSIDE:

android:scaleType="centerInside"

public static final ImageView.ScaleType CENTER_INSIDE

Added in API level 1 Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding). The image is then centered in the view. From XML, use this syntax: android:scaleType="centerInside".

also

The issue may be that adjustViewBounds will not increase the size of the ImageView beyond the natural dimensions of the drawable.

Upvotes: 1

Related Questions