图片与图标 (Image)
1. 显示本地资源
使用 Image Composable 显示 Drawable 资源或 Bitmap。
kotlin
Image(
painter = painterResource(id = R.drawable.profile_picture),
contentDescription = "用户头像", // 用于无障碍,装饰性图片可传 null
modifier = Modifier.size(100.dp).clip(CircleShape), // 圆形裁剪
contentScale = ContentScale.Crop // 缩放模式:CenterCrop
)缩放模式 (ContentScale)
| 模式 | 描述 |
|---|---|
Crop | 保持纵横比缩放,填满容器,裁剪多余部分 |
Fit | 保持纵横比缩放,完整显示在容器内(可能有留白) |
FillBounds | 拉伸填满容器,不保持纵横比 |
2. 显示图标 (Icon)
Icon 组件专门用于显示单色矢量图标(VectorDrawable)。它会自动应用 LocalContentColor(例如在 Button 内部自动变白)。
kotlin
Icon(
imageVector = Icons.Default.Home, // 使用内置 Material 图标
contentDescription = "主页",
tint = Color.Red // 自定义着色
)依赖
如果要使用全部 Material 图标(如 Icons.Filled.AccountCircle),需引入扩展库: implementation("androidx.compose.material:material-icons-extended:1.6.0")
3. 加载网络图片 (Coil)
Compose 官方推荐使用 Coil 库加载网络图片。
kotlin
implementation("io.coil-kt:coil-compose:2.6.0")kotlin
AsyncImage(
model = "https://example.com/image.jpg",
contentDescription = null,
modifier = Modifier.size(150.dp),
placeholder = painterResource(R.drawable.placeholder), // 加载中占位图
error = painterResource(R.drawable.error), // 错误占位图
contentScale = ContentScale.Crop
)kotlin
// 当你需要根据加载状态自定义复杂 UI 时
SubcomposeAsyncImage(
model = "https://example.com/image.jpg",
contentDescription = null,
) {
val state = painter.state
if (state is AsyncImagePainter.State.Loading || state is AsyncImagePainter.State.Error) {
CircularProgressIndicator()
} else {
SubcomposeAsyncImageContent()
}
}