简体   繁体   中英

Android ImageView scale bitmap to the width and crop the height

I have a fixed size ImageView . I want to achieve this :

  1. Scale the Bitmap always to the width, if the Bitmap is wider or smaller than Imageview width.
  2. Crop the height if taller than ImageView height else scale it to the height.

I want something like this answer , but the other way around (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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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