从磁盘加载图片
使用 Image
可组合项在屏幕上显示图形。要从磁盘加载图片(例如:PNG、JPEG、WEBP)或矢量资源,请使用 painterResource
API 和您的图片引用。您无需了解资源类型,只需在 Image
或 paint
修饰符中使用 painterResource
即可。
DrawScope
:
Image( painter = painterResource(id = R.drawable.dog), contentDescription = stringResource(id = R.string.dog_content_description) )
为确保您的应用具有无障碍功能,请为屏幕上的可视元素提供 contentDescription
。对讲功能会朗读内容说明,因此您必须确保文本在朗读和翻译后具有意义。在上面的示例中,stringResource()
用于从 strings.xml
文件加载已翻译的内容说明。如果屏幕上的可视元素纯粹是装饰性的,请将其 contentDescription
设置为 null
,以便屏幕阅读器忽略它。
如果您需要更底层的 ImageBitmap
特有功能,可以使用 ImageBitmap.imageResource()
来加载位图。如需详细了解 ImageBitmap,请阅读ImageBitmap 与 ImageVector 部分。
Drawable 支持
painterResource
当前支持以下 drawable 类型
AnimatedVectorDrawable
BitmapDrawable
(PNG、JPG、WEBP)ColorDrawable
VectorDrawable
从互联网加载图片
要从互联网加载图片,有多个第三方库可帮助您处理此过程。图片加载库为您完成了大量繁重工作;它们负责缓存(因此您无需多次下载图片)和网络逻辑以下载图片并将其显示在屏幕上。
例如,要使用 Instacart 的 Coil 加载图片,请将该库添加到您的 gradle 文件中,然后使用 AsyncImage
从网址加载图片。
AsyncImage( model = "https://example.com/image.jpg", contentDescription = "Translated description of what the image contains" )
其他资源
为您推荐
- 注意:禁用 JavaScript 时会显示链接文本
- Compose 中的资源
- Compose 中的无障碍功能
- Compose 中的图形