简体   繁体   English

Android ImageView将位图缩放到宽度并裁剪高度

[英]Android ImageView scale bitmap to the width and crop the height

I have a fixed size ImageView . 我有一个固定大小的ImageView I want to achieve this : 我想实现这一目标:

  1. Scale the Bitmap always to the width, if the Bitmap is wider or smaller than Imageview width. 缩放Bitmap总是向宽度,如果Bitmap是比更宽或更小Imageview宽度。
  2. Crop the height if taller than ImageView height else scale it to the height. 如果高度大于ImageView的高度,则裁剪高度,否则将其缩放为该高度。

I want something like this answer , but the other way around (FitXCropY). 我想要类似这个答案的东西,但是反过来(FitXCropY)。 I have tried changing this answer with no success. 我尝试更改此答案没有成功。

Thank you. 谢谢。

Based on this answer ImageView to scale to fixed height, but crop excess width 根据此答案ImageView缩放到固定的高度,但裁剪多余的宽度

public class FitXCropYImageView extends ImageView {
boolean done = false;

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

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

@SuppressWarnings("UnusedDeclaration")
public FitXCropYImageView(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 viewHalfHeight = viewHeight / 2;
    float scale = (float) viewWidth / (float) drawableWidth;
    float scaledHeight = drawableHeight * scale;
    float scaledHalfHeight = scaledHeight / 2;
    viewRect.set(0, viewHalfHeight-scaledHalfHeight,viewWidth, viewHalfHeight+scaledHalfHeight);

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

    done = true;

    requestLayout();
}
}

Try like this, 这样尝试

Add inside Oncreate 在内部添加Oncreate

viewImage = (ImageView) findViewById(R.id.pictureImageview123);
viewImage.setScaleType(ScaleType.FIT_XY);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM