簡體   English   中英

Android ImageView將位圖縮放到寬度並裁剪高度

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

我有一個固定大小的ImageView 我想實現這一目標:

  1. 縮放Bitmap總是向寬度,如果Bitmap是比更寬或更小Imageview寬度。
  2. 如果高度大於ImageView的高度,則裁剪高度,否則將其縮放為該高度。

我想要類似這個答案的東西,但是反過來(FitXCropY)。 我嘗試更改此答案沒有成功。

謝謝。

根據此答案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();
}
}

這樣嘗試

在內部添加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