我有一个固定的尺寸ImageView
。我想实现这个目标:
Bitmap
宽于或小于Bitmap
宽度,则Imageview
始终缩放到宽度。ImageView
高度,则裁剪高度,否则将其缩放到高度。我想要这样的answer,但反过来(FitXCropY)。我试过改变这个答案没有成功。
谢谢。
答案 0 :(得分:1)
根据这个答案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();
}
}
答案 1 :(得分:-1)
试试这个,
在Oncreate中添加
viewImage = (ImageView) findViewById(R.id.pictureImageview123);
viewImage.setScaleType(ScaleType.FIT_XY);