自定义图片

可以通过 Image 可组合项(contentScalecolorFilter)的属性来自定义图片。您还可以应用现有修饰符来为您的 Image 应用不同的效果。修饰符可用于任何可组合项,而不仅仅是 Image 可组合项,而 contentScalecolorFilter 则是 Image 可组合项上的显式参数。

内容缩放

指定 contentScale 选项以裁剪或更改图片在其边界内的缩放方式。默认情况下,如果您未指定 contentScale 选项,则会使用 ContentScale.Fit

在以下示例中,Image 可组合项限制为 150dp 大小,带有边框,并且在 Image 可组合项上将背景设置为黄色,以展示下表中的不同 ContentScale 选项。

val imageModifier = Modifier
    .size(150.dp)
    .border(BorderStroke(1.dp, Color.Black))
    .background(Color.Yellow)
Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    contentScale = ContentScale.Fit,
    modifier = imageModifier
)

设置不同的 ContentScale 选项会产生不同的输出。下表可帮助您选择所需的正确 ContentScale 模式

源图片 Portrait source image Source image landscape
ContentScale 结果 - 竖向图片 结果 - 横向图片
ContentScale.Fit:均匀缩放图片,保持宽高比(默认)。如果内容小于尺寸,图片会放大以适应边界。 ContentScale.Fit portrait ContentScale.Fit landscape
ContentScale.Crop:将图片居中裁剪到可用空间内。 ContentScale.Crop portrait ContentScale.Crop landscape
ContentScale.FillHeight:保持宽高比缩放源,使边界与目标高度匹配。 ContentScale.FillHeight portrait ContentScale.FillHeight landscape
ContentScale.FillWidth:保持宽高比缩放源,使边界与目标宽度匹配。 ContentScale.FillWidth portrait ContentScale.FillWidth landscape
ContentScale.FillBounds:**非均匀地**垂直和水平缩放内容以填充目标边界。(注意:如果您将图片放置在与图片确切比例不匹配的容器中,这会使图片失真) ContentScale.FillBounds portrait ContentScale.FillBounds landscape
ContentScale.Inside:缩放源以在目标边界内保持宽高比。如果源在两个维度上都小于或等于目标,其行为类似于 `None`。内容将始终包含在边界内。如果内容小于边界,则不会应用任何缩放。 源图片大于边界:ContentScale.Inside 竖向,源图片大于边界 源图片小于边界:ContentScale.Inside 竖向,源图片小于边界 源图片大于边界:ContentScale.Inside 横向,源图片大于边界 源图片小于边界:ContentScale.Inside 横向,源图片小于边界
ContentScale.None:不对源应用任何缩放。如果内容小于目标边界,它不会放大以适应区域。 源图片大于边界:ContentScale.None 竖向,源图片大于边界 源图片小于边界:ContentScale.None 竖向,源图片小于边界 源图片大于边界:ContentScale.None 横向,源图片大于边界 源图片小于边界:ContentScale.None 横向,源图片小于边界

Image 可组合项裁剪为形状

要使图片适合某个形状,请使用内置的 clip 修饰符。要将图片裁剪成圆形,请使用 Modifier.clip(CircleShape)

Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    contentScale = ContentScale.Crop,
    modifier = Modifier
        .size(200.dp)
        .clip(CircleShape)
)

Clipping an image with CircleShape
图 1:使用 CircleShape 裁剪图片

圆角形状 - 使用 Modifier.clip(RoundedCornerShape(16.dp)),并指定您希望圆角的尺寸

Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    contentScale = ContentScale.Crop,
    modifier = Modifier
        .size(200.dp)
        .clip(RoundedCornerShape(16.dp))
)

Clipping an image with RoundedCornerShape
图 2:使用 RoundedCornerShape 裁剪图片

您还可以通过扩展 Shape 并提供 Path 来创建自己的裁剪形状,以便形状围绕其裁剪

class SquashedOval : Shape {
    override fun createOutline(
        size: Size,
        layoutDirection: LayoutDirection,
        density: Density
    ): Outline {
        val path = Path().apply {
            // We create an Oval that starts at ¼ of the width, and ends at ¾ of the width of the container.
            addOval(
                Rect(
                    left = size.width / 4f,
                    top = 0f,
                    right = size.width * 3 / 4f,
                    bottom = size.height
                )
            )
        }
        return Outline.Generic(path = path)
    }
}

Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    contentScale = ContentScale.Crop,
    modifier = Modifier
        .size(200.dp)
        .clip(SquashedOval())
)

Clipping an image with custom path shape
图 3:使用自定义路径形状裁剪图片

Image 可组合项添加边框

一项常见操作是将 Modifier.border()Modifier.clip() 结合使用,为图片创建边框

val borderWidth = 4.dp
Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    contentScale = ContentScale.Crop,
    modifier = Modifier
        .size(150.dp)
        .border(
            BorderStroke(borderWidth, Color.Yellow),
            CircleShape
        )
        .padding(borderWidth)
        .clip(CircleShape)
)

Clip an image and provide a border around it
图 4:裁剪图片并为其添加边框

如果您希望创建渐变边框,可以使用 Brush API 在图片周围绘制彩虹渐变边框

val rainbowColorsBrush = remember {
    Brush.sweepGradient(
        listOf(
            Color(0xFF9575CD),
            Color(0xFFBA68C8),
            Color(0xFFE57373),
            Color(0xFFFFB74D),
            Color(0xFFFFF176),
            Color(0xFFAED581),
            Color(0xFF4DD0E1),
            Color(0xFF9575CD)
        )
    )
}
val borderWidth = 4.dp
Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    contentScale = ContentScale.Crop,
    modifier = Modifier
        .size(150.dp)
        .border(
            BorderStroke(borderWidth, rainbowColorsBrush),
            CircleShape
        )
        .padding(borderWidth)
        .clip(CircleShape)
)

Rainbow gradient circle border
图 5:彩虹渐变圆形边框

设置自定义宽高比

要将图片转换为自定义宽高比,请使用 Modifier.aspectRatio(16f/9f) 为图片(或任何可组合项)提供自定义比例。

Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    modifier = Modifier.aspectRatio(16f / 9f)
)

Using Modifier.aspectRatio(16f/9f) on Image
图 6:在 Image 上使用 Modifier.aspectRatio(16f/9f)

颜色滤镜 - 转换图片的像素颜色

Image 可组合项有一个 colorFilter 参数,可以更改图片单个像素的输出。

为图片着色

使用 ColorFilter.tint(color, blendMode) 会将给定颜色与混合模式应用到您的 Image 可组合项上。ColorFilter.tint(color, blendMode) 使用 BlendMode.SrcIn 为内容着色,这意味着所提供的颜色会在屏幕上显示图片的位置显示。这对于需要不同主题的图标和矢量图很有用。

Image(
    painter = painterResource(id = R.drawable.baseline_directions_bus_24),
    contentDescription = stringResource(id = R.string.bus_content_description),
    colorFilter = ColorFilter.tint(Color.Yellow)
)

ColorFilter.tint applied with BlendMode.SrcIn
图 7:应用了 BlendMode.SrcIn 的 ColorFilter.tint

其他 BlendMode 会产生不同的效果。例如,在图片上使用 Color.Green 设置 BlendMode.Darken 会产生以下结果

Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    colorFilter = ColorFilter.tint(Color.Green, blendMode = BlendMode.Darken)
)

Color.Green tint with BlendMode.Darken
图 8:BlendMode.Darken 的 Color.Green 色调

如需了解有关可用不同混合模式的更多信息,请参阅 BlendMode 参考文档

使用颜色矩阵应用 Image 滤镜

使用颜色矩阵 ColorFilter 选项转换您的图片。例如,要为图片应用黑白滤镜,您可以使用 ColorMatrix 并将饱和度设置为 0f

Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    colorFilter = ColorFilter.colorMatrix(ColorMatrix().apply { setToSaturation(0f) })
)

Color Matrix with saturation 0 (black and white image)
图 9:饱和度为 0 的颜色矩阵(黑白图片)

调整 Image 可组合项的对比度或亮度

要更改图片的对比度和亮度,您可以使用 ColorMatrix 来更改值

val contrast = 2f // 0f..10f (1 should be default)
val brightness = -180f // -255f..255f (0 should be default)
val colorMatrix = floatArrayOf(
    contrast, 0f, 0f, 0f, brightness,
    0f, contrast, 0f, 0f, brightness,
    0f, 0f, contrast, 0f, brightness,
    0f, 0f, 0f, 1f, 0f
)
Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    colorFilter = ColorFilter.colorMatrix(ColorMatrix(colorMatrix))
)

Adjusted image brightness and contrast using ColorMatrix
图 10:使用 ColorMatrix 调整后的图片亮度和对比度

反转 Image 可组合项的颜色

要反转图片的颜色,请将 ColorMatrix 设置为反转颜色

val colorMatrix = floatArrayOf(
    -1f, 0f, 0f, 0f, 255f,
    0f, -1f, 0f, 0f, 255f,
    0f, 0f, -1f, 0f, 255f,
    0f, 0f, 0f, 1f, 0f
)
Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    colorFilter = ColorFilter.colorMatrix(ColorMatrix(colorMatrix))
)

Inverted colors on image
图 11:图片颜色反转

模糊 Image 可组合项

要模糊图片,请使用 Modifier.blur(),并提供 radiusXradiusY,它们分别指定水平和垂直方向上的模糊半径。

Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    contentScale = ContentScale.Crop,
    modifier = Modifier
        .size(150.dp)
        .blur(
            radiusX = 10.dp,
            radiusY = 10.dp,
            edgeTreatment = BlurredEdgeTreatment(RoundedCornerShape(8.dp))
        )
)

BlurEffect applied to image
图 12:应用于图片的 BlurEffect

模糊 Image 时,建议使用 BlurredEdgeTreatment(Shape),而不是 BlurredEdgeTreatment.Unbounded,因为后者用于模糊预计将呈现到原始内容边界之外的任意渲染。对于图片而言,它们很可能不会呈现到内容边界之外;而模糊圆角矩形可能需要这种区别。

例如,如果我们将上述图片上的 BlurredEdgeTreatment 设置为 Unbounded,则图片的边缘会显得模糊而非清晰

Image(
    painter = painterResource(id = R.drawable.dog),
    contentDescription = stringResource(id = R.string.dog_content_description),
    contentScale = ContentScale.Crop,
    modifier = Modifier
        .size(150.dp)
        .blur(
            radiusX = 10.dp,
            radiusY = 10.dp,
            edgeTreatment = BlurredEdgeTreatment.Unbounded
        )
        .clip(RoundedCornerShape(8.dp))
)

BlurEdgeTreatment.Unbounded
图 13:BlurEdgeTreatment.Unbounded