如果圖像太小可能會成爲一個問題,因爲它不適合屏幕尺寸。
我使用這個類來解決這個問題:
public class FixedCenterCrop extends ImageView {
public FixedCenterCrop(Context context) {
super(context);
setScaleType(ScaleType.MATRIX);
}
public FixedCenterCrop(Context context, AttributeSet attrs) {
super(context, attrs);
setScaleType(ScaleType.MATRIX);
}
public FixedCenterCrop(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setScaleType(ScaleType.MATRIX);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
recomputeImgMatrix();
}
@Override
protected boolean setFrame(int l, int t, int r, int b) {
recomputeImgMatrix();
return super.setFrame(l, t, r, b);
}
private void recomputeImgMatrix() {
final Matrix matrix = getImageMatrix();
float scale;
final int viewWidth = getWidth() - getPaddingLeft() - getPaddingRight();
final int viewHeight = getHeight() - getPaddingTop() - getPaddingBottom();
final int drawableWidth = getDrawable().getIntrinsicWidth();
final int drawableHeight = getDrawable().getIntrinsicHeight();
if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
scale = (float) viewHeight/(float) drawableHeight;
} else {
scale = (float) viewWidth/(float) drawableWidth;
}
matrix.setScale(scale, scale);
matrix.postTranslate((viewWidth - drawableWidth * scale)/2, (viewHeight - drawableHeight*scale)/2);
setImageMatrix(matrix);
}
}
沒錯,+1它 –
非常感謝。 'android:scaleType =「centerCrop」'完全適合我。 –