ImageView that is a fixed size, regardless of image size
I have an ImageView which I want to always be the same size. If the image is smaller than the view, I'd like it to be centred in the view. If the Image is larger than the view then I'd like it scaled down - with asp开发者_运维技巧ect ratio preserved.
I've had several attempts at this myself - the latest of which is:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="@+id/itemImage" android:layout_width="100dp"
android:layout_height="100dp" android:scaleType="fitCenter"
android:adjustViewBounds="true" android:gravity="center" android:padding="10px" />
<TextView android:id="@+id/currentLentItem" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:padding="10px"/>
</LinearLayout>
What am I missing here?
Try using the scale type centerInside
, like below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView
android:id="@+id/itemImage"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentRight="true"
android:scaleType="centerInside"
android:gravity="right|center_vertical"
android:padding="10px"
/>
<TextView
android:id="@+id/currentLentItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/list_image"
android:padding="10px"
/>
</RelativeLayout>
This causes the image to scale down only if larger than the layout, and it will scale proportionally as well (whereas fitXY scales without regard to aspect ratio). It will also center the image if smaller.
EDIT: I've updated the example for something like you're wanting. Here's the gist of what changed:
• ImageView gravity changed to right|center_vertical
. Since you want them to align on the right, using this gravity will allow that even if they are portrait orientation images.
• ImageView aligned to the right of the RelativeLayout
• RelativeLayout set to wrap_content
since it's to be used for a ListView.
• TextView added, aligned to the parent's left, with its right edge defined by the left edge of itemImage.
If the image is larger than the view, then you could scale it using:
android:scaleType="fitXY"
That won't give you what you want if the image is smaller. Perhaps you could detect that in runtime and change the scaleType programmatically.
精彩评论