ImageView缩放到固定高度,但裁剪多余的宽度

Maa*_*ten 9 android android-imageview

我希望我ImageView以特定的方式扩展:

  • 缩放,使图像的高度始终适合的高度 ImageView
  • 裁剪任何多余的宽度

一张图片的声音大于1000字,所以这里是我想要ImageView表现的方式.假设它有一个固定的高度,比如100dp,假设它的宽度是match_parent.

在此输入图像描述

注意

  • 在手机布局上,图像高度被拉伸,但两侧被裁剪,类似于CROP_CENTER.
  • 在平板电脑布局上,图像也被拉伸以适应ImageView高度,表现得像FIT_CENTER

我怀疑我需要scaleType:matrix,但在那之后我迷失了.如何确保图像适合Y,但作物X?

Gen*_* Bo 19

在xml中,使用:

    android:scaleType="centerCrop"
    android:adjustViewBounds="true"
Run Code Online (Sandbox Code Playgroud)

来自并感谢:https://stackoverflow.com/a/15600295/2162226


Maa*_*ten 5

在我的朋友Carlos Robles和pskink的帮助下,提出了以下习惯ImageView:

public class FitYCropXImageView extends ImageView {
    boolean done = false;

    @SuppressWarnings("UnusedDeclaration")
    public FitYCropXImageView(Context context) {
        super(context);
        setScaleType(ScaleType.MATRIX);
    }

    @SuppressWarnings("UnusedDeclaration")
    public FitYCropXImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setScaleType(ScaleType.MATRIX);
    }

    @SuppressWarnings("UnusedDeclaration")
    public FitYCropXImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setScaleType(ScaleType.MATRIX);
    }

    private final RectF drawableRect = new RectF(0, 0, 0,0);
    private final RectF viewRect = new RectF(0, 0, 0,0);
    private final Matrix m = new Matrix();
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (done) {
            return;//Already fixed drawable scale
        }
        final Drawable d = getDrawable();
        if (d == null) {
            return;//No drawable to correct for
        }
        int viewHeight = getMeasuredHeight();
        int viewWidth = getMeasuredWidth();
        int drawableWidth = d.getIntrinsicWidth();
        int drawableHeight = d.getIntrinsicHeight();
        drawableRect.set(0, 0, drawableWidth, drawableHeight);//Represents the original image
        //Compute the left and right bounds for the scaled image
        float viewHalfWidth = viewWidth / 2;
        float scale = (float) viewHeight / (float) drawableHeight;
        float scaledWidth = drawableWidth * scale;
        float scaledHalfWidth = scaledWidth / 2;
        viewRect.set(viewHalfWidth - scaledHalfWidth, 0, viewHalfWidth + scaledHalfWidth, viewHeight);

        m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER /* This constant doesn't matter? */);
        setImageMatrix(m);

        done = true;

        requestLayout();
    }
}
Run Code Online (Sandbox Code Playgroud)