使用 Coil 在宽度上缩放图像并在高度上裁剪图像

问题描述 投票:0回答:1

我有一个具有固定高度(400dp)和可变宽度(与父级匹配)的ImageView。我正在使用 Coil 从网络加载内容。

我有一些风景图像和其他肖像图像。

我想始终适应宽度并裁剪高度:

我听不懂。

如果我使用 CenterCrop,如果太大,图像会在宽度上被裁剪

如果我使用 CenterFit,如果图像太高,则图像不适合宽度

获得所需行为的最佳方法是什么?

我尝试在 ImageView 和 Coil 加载器上使用所有可能的 ScaleType。

android imageview coil
1个回答
0
投票

像这样定制

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
替换为您的包名称。

© www.soinside.com 2019 - 2024. All rights reserved.