在this link找到答案。
基本上,使用的技巧是在 Java 中创建一个自定义 ImageView 类,然后使用它。如有必要,它将根据情况计算正确的裁剪区域。
如果有人找到纯 XML 解决方案,请随时告诉我!
不用再等待,这是我使用的代码。
JAVA 类
public class FitYCropXImageView extends ImageView {
boolean done = false;
@SuppressWarnings("UnusedDeclaration")
public FitYCropXImageView(Context context) {
super(context);
setScaleType(ScaleType.MATRIX);
}
@SuppressWarnings("UnusedDeclaration")
public FitYCropXImageView(Context context, AttributeSet attrs) {
super(context, attrs);
setScaleType(ScaleType.MATRIX);
}
@SuppressWarnings("UnusedDeclaration")
public FitYCropXImageView(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 viewHalfWidth = viewWidth / 2;
float scale = (float) viewHeight / (float) drawableHeight;
float scaledWidth = drawableWidth * scale;
float scaledHalfWidth = scaledWidth / 2;
viewRect.set(viewHalfWidth - scaledHalfWidth, 0, viewHalfWidth + scaledHalfWidth, viewHeight);
m.setRectToRect(drawableRect, viewRect, Matrix.ScaleToFit.CENTER /* This constant doesn't matter? */);
setImageMatrix(m);
done = true;
requestLayout();
}
}
XML
<com.app.YourAppName.YourAppName.CustomViews.FitYCropXImageView
android:id="@+id/user_pic"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"
android:elevation="2dp"
/>
必要时的 JAVA 活动
import com.app.YourAppName.YourAppName.CustomViews.FitYCropXImageView;
FitYCropXImageView profilePic = (FitYCropXImageView) findViewById(R.id.user_pic);