翻译:English
Target 主要的工作是用来显示 Image,同时还负责在构建 ImageRequest 时提供 SizeResolver、ScaleDecider、ResizeOnDrawHelper、LifecycleResolver 等属性,这些属性会被作为默认值使用
将 Image 显示到 Compose 组件时不需要你主动设置 target,AsyncImage 和 AsyncImagePainter 会设置,你只需设置其它参数即可,如下:
AsyncIage(
rqeuest = ComposableImageRequest("https://example.com/image.jpg") {
placeholder(Res.drawable.placeholder)
crossfade()
},
contentDescription = "photo",
)
Tip
placeholder(Res.drawable.placeholder)
需要导入 sketch-compose-resources
模块
将 Image 显示到 View 时需要你主动设置 Target
Sketch 提供了 ImageViewTarget 用来将图片显示到 [ImageView],如下:
ImageRequest(context, "https://www.example.com/image.jpg") {
placeholder(R.drawable.placeholder)
crossfade()
target(imageView)
}.enqueue(request)
Sketch 还提供了 RemoteViewsTarget 用来将图片显示到 RemoteViews,如下:
val remoteViews =
RemoteViews(context.packageName, R.layout.remote_views_notification)
val notification = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID).apply {
setSmallIcon(R.mipmap.ic_launcher)
setContent(remoteViews)
}.build()
ImageRequest(context, "https://www.example.com/image.jpg") {
resize(100.dp2px, 100.dp2px, scale = START_CROP)
target(
RemoteViewsTarget(
remoteViews = remoteViews,
imageViewId = R.id.remoteViewsNotificationImage,
ignoreNullDrawable = true,
onUpdated = {
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(1101, notification)
}
)
)
}.enqueue()
Tip
- 如上所示 RemoteViewsTarget 仅将 Drawable 转换为 Bitmap 并调用 RemoteViews 的 setImageViewBitmap 方法设置 Bitmap
- 所以还需要你在 onUpdated 函数中刷新通知或 AppWidget 才能将 Bitmap 显示到屏幕上