class TopCropImageView : AppCompatImageView {
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
init()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
recomputeImgMatrix()
}
override fun setFrame(l: Int, t: Int, r: Int, b: Int): Boolean {
recomputeImgMatrix()
return super.setFrame(l, t, r, b)
}
private fun init() {
scaleType = ScaleType.MATRIX
}
private fun recomputeImgMatrix() {
val drawable = drawable ?: return
val matrix = imageMatrix
val scale: Float
val viewWidth = width - paddingLeft - paddingRight
val viewHeight = height - paddingTop - paddingBottom
val drawableWidth = drawable.intrinsicWidth
val drawableHeight = drawable.intrinsicHeight
scale = if (drawableWidth * viewHeight > drawableHeight * viewWidth) {
viewHeight.toFloat() / drawableHeight.toFloat()
} else {
viewWidth.toFloat() / drawableWidth.toFloat()
}
matrix.setScale(scale, scale)
imageMatrix = matrix
}
}
顶部将对齐,底部的视图将被裁剪。
尝试使用scaleType="fitStart"
使用Matrix.ScaleToFit.START缩放图像
Matrix.ScaleToFit.START:计算一个比例,保持原始src纵横比,但也确保src完全适合dst。至少一个轴(X或Y)将完全适合。START将结果与dst的左侧和顶部边缘对齐。
参考链接:https://robots.thoughtbot.com/android-imageview-scaletype-a-visual-guide#fit_start
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/image">
或者在Java中使用自定义矩阵
if (imageView.getScaleType() != ImageView.ScaleType.MATRIX) {
imageView.setScaleType(ImageView.ScaleType.MATRIX);
}
Matrix m = imageView.getImageMatrix();
int dw = imageView.getDrawable().getIntrinsicWidth();
int dh = imageView.getDrawable().getIntrinsicHeight();
int msWidth, msHeight;
float scalew, scaleh;
Display display = activity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
msWidth = size.x;
if (imageView.getLayoutParams().width == ViewGroup.LayoutParams.WRAP_CONTENT) {
msWidth = dw < msWidth ? dw : msWidth;
}
scalew = (float) msWidth / dw;
msHeight = size.y;
if (imageView.getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) {
msHeight = dh < msHeight ? dh : msHeight;
}
scaleh = (float) msHeight / dh;
float scale = Math.max(scalew, scaleh);
m.setScale(scale, scale);
m.postTranslate(0, 0);
imageView.setImageMatrix(m);
}