3

我在这个网站上找到了很多答案,但它们不起作用或仅适用于单个案例。就我而言:

  • 我想加载图像并将其显示到 ImageView 中。
  • ImageView 的宽度必须是可能的最大值:父布局宽度。
  • 高度必须是允许重新缩放图像并保持纵横比的高度。

如何做到这一点?这是我的内部带有 ImageView 的布局(目前我一直在使用 fitXY 但图像不保留纵横比,即使使用了adjustViewBounds:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layoutPictureGalleryItem"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:background="#E0E0DE"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        tools:ignore="ContentDescription" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#FFFFFF" >

        <TextView
            android:id="@+id/textName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="esto es una prueba para ver cómo queda el layout"
            android:textColor="#000000"
            android:textSize="12sp"
            android:typeface="serif"
            android:padding="2dp" />

        <TextView
            android:id="@+id/textDescription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:padding="2dp" />

    </LinearLayout>

</LinearLayout>
4

1 回答 1

4

使用此小部件而不是您的 imageview 并让宽度与父级匹配:

package com.myapp.widgets;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ResizableImageView extends ImageView {

public ResizableImageView(Context context)
{
    super(context);
}

public ResizableImageView(Context context, AttributeSet attrs)
{
    super(context, attrs);
}

public ResizableImageView(Context context, AttributeSet attrs,
        int defStyle)
{
    super(context, attrs, defStyle);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    Drawable drawable = getDrawable();
    if (drawable != null)
    {
        int width =  MeasureSpec.getSize(widthMeasureSpec);
        int diw = drawable.getIntrinsicWidth();
        if (diw > 0)
        {
            int height = width * drawable.getIntrinsicHeight() / diw;
            setMeasuredDimension(width, height);
        }
        else
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    else
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
于 2013-08-28T15:11:30.207 回答