android-imageview - Android - 缩放 ImageView 以使其宽度始终为 100 dip

标签 android-imageview android

我正在尝试让 ImageView 具有特定的宽度(比如 100dips),但要进行缩放以便高度是保持比例的任何值,所以如果 4:3 则 75 dips,如果 4:5 则 120蘸料等

我尝试了一些方法,但没有任何效果。这是我目前的尝试:

<ImageView
      android:id="@+id/image"
      android:layout_height="wrap_content"
      android:layout_width="100dip"
      android:adjustViewBounds="true"
       android:src="@drawable/stub" 
       android:scaleType="fitCenter" />

高度的 wrap_content 并没有改善,它只是让整个图像变小(但保持纵横比)。我怎样才能完成我想做的事情?

最佳答案

将以下类添加到您的项目中并像这样更改您的布局

查看

<my.package.name.AspectRatioImageView
    android:layout_centerHorizontal="true"
    android:src="@drawable/my_image"
    android:id="@+id/my_image"
    android:layout_height="wrap_content"
    android:layout_width="100dp"
    android:adjustViewBounds="true" />

package my.package.name;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * ImageView which scales an image while maintaining
 * the original image aspect ratio
 *
 */
public class AspectRatioImageView extends ImageView {

    /**
     * Constructor
     * 
     * @param Context context
     */
    public AspectRatioImageView(Context context) {

        super(context);
    }

    /**
     * Constructor
     * 
     * @param Context context
     * @param AttributeSet attrs
     */
    public AspectRatioImageView(Context context, AttributeSet attrs) {

        super(context, attrs);
    }

    /**
     * Constructor
     * 
     * @param Context context
     * @param AttributeSet attrs
     * @param int defStyle
     */
    public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle);
    }

    /**
     * Called from the view renderer.
     * Scales the image according to its aspect ratio.
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
        setMeasuredDimension(width, height);
    }
}

关于android-imageview - Android - 缩放 ImageView 以使其宽度始终为 100 dip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10153611/

相关文章:

机器人 : Display image in imageview from another imageview source?

android - RelativeLayout 中的 ImageView 具有顶部和底部填充

android - 设置其他布局参数imageview

android - ListView ImageButton 设置铃声

java - 在 Activity 之间传递 ResourceId 作为整数

android - 在 Android 自定义 View 中调用 obtainStyledAttributes() 的正确方法是什么

android - 我只有一个 mipmap 目录。 (xhdpi、mdpi、xxhdpi 等缺失)

android - Gallery 和 Camera-taken-photo 的 URI/URL 路径不同

android - 折叠工具栏布局 |滚动和布局问题

android - 如何处理 diffrent-2 屏幕分辨率 android 的 xml UI