Android规模ImageView的框架

时间:2017-01-07 12:46:26

标签: android

我有一个imageview,我想用它的框架缩放它! 我使用imageView.setScaleX(),但这种方法只能缩放图像,图像视图X,Y,宽度和高度是相同的。 如何使用图片调整imageview的大小?

see this figure

3 个答案:

答案 0 :(得分:0)

您可以将属性scaleType添加到ImageView XML,如下所示:

android:scaleType="fitXY"

更多信息:

https://robots.thoughtbot.com/android-imageview-scaletype-a-visual-guide

https://developer.android.com/reference/android/widget/ImageView.ScaleType.html

答案 1 :(得分:0)

感谢@saeid。我用setWidth替换了setScale并解决了我的问题。

答案 2 :(得分:0)

如果您想在宽度更改时自动更改高度,请使用此自定义ImageView。

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

import java.lang.reflect.Field;

public class AspectRatioImageView extends ImageView {

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

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        try {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = width * getDrawable().getIntrinsicHeight()
                    / getDrawable().getIntrinsicWidth();
            int maxHeight;
            try {
                Field f = ImageView.class.getDeclaredField("mMaxHeight");
                f.setAccessible(true);
                maxHeight = (Integer) f.get(this);
            } catch (NoSuchFieldException e) {
                maxHeight = Integer.MAX_VALUE;
            }
            setMeasuredDimension(width, height > maxHeight ? maxHeight : height);
        } catch (Exception e) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}
相关问题