我有一个具有固定高度(400dp)和可变宽度(与父级匹配)的ImageView。我正在使用 Coil 从网络加载内容。
我有一些风景图像和其他肖像图像。
我想始终适应宽度并裁剪高度:
我听不懂。
如果我使用 CenterCrop,如果太大,图像会在宽度上被裁剪
如果我使用 CenterFit,如果图像太高,则图像不适合宽度
获得所需行为的最佳方法是什么?
我尝试在 ImageView 和 Coil 加载器上使用所有可能的 ScaleType。
像这样定制
ImageView
:
class CustomImageView(context: Context, attrs: AttributeSet) : AppCompatImageView(context, attrs) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = measuredWidth
val height = measuredHeight
if (width > height) {
setMeasuredDimension(width, width)
} else {
setMeasuredDimension(height, height)
}
}
}
在您的布局中使用它,如下所示:
<com.example.CustomImageView
android:layout_width="match_parent"
android:layout_height="400dp"
android:scaleType="centerCrop" />
并使用 Coil 将图像加载到此
CustomImageView
。
将
com.example
替换为您的包名称。