【问题标题】:How to clip an image to remove its padding如何剪辑图像以删除其填充
【发布时间】:2021-11-25 13:31:21
【问题描述】:

我正在替换 YouTube 上的缩略图。这些图像的顶部和底部都有黑色矩形。

我想显示没有矩形的图像。如何设置垂直“填充”以删除黑色矩形。

Image(
       painter = rememberImagePainter("https://img.youtube.com/vi/RS6By_pE7uo/0.jpg"),
       modifier = Modifier
            .width(itemWidth)
            .height(photoImageHeight)
       contentScale = ContentScale.FillBounds
 )

【问题讨论】:

  • 我想不出任何办法从图像中删除这些矩形。我想您可以将您的Image 包装在Box 中以及另外两个盒子(一个用于顶部,一个用于底部),并将一些固定的小高度和背景设置为您的屏幕背景。这些框将隐藏图像的顶部和底部。

标签: android android-studio kotlin android-jetpack-compose android-jetpack


【解决方案1】:

将图像放置在与图像宽度相同但高度减少了图像上方和下方黑条使用的高度量的 Box 中。然后使用cropToBounds:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            val w = 480f / LocalDensity.current.density * 2.7f
            val h = 360 / LocalDensity.current.density * 2.7f

            Box(
                modifier = Modifier
                    .requiredWidth(w.dp)
                    .requiredHeight(h.dp - 70.dp)
                    .clip(shape= RoundedCornerShape(30.dp))
            ) {
                Image(
                    modifier = Modifier
                        .requiredWidth(w.dp)
                        .requiredHeight(h.dp),
                    painter = rememberImagePainter(
                        data = "https://img.youtube.com/vi/RS6By_pE7uo/0.jpg",
                    ),
                    contentDescription = null,
                    contentScale = ContentScale.FillWidth,
                )
            }
        }
    }
}

【讨论】:

  • 我更新了代码。它在所有角上显示圆角。我只用剪辑替换了 clipToBounds。