Skip to content

Latest commit

 

History

History
105 lines (75 loc) · 3.96 KB

target.md

File metadata and controls

105 lines (75 loc) · 3.96 KB

Target

Target 用来接收 ImageRequest 的结果 ImageResult,并将结果应用到目标上

从前面的 入门 文档可以知道 ImageRequest 分为 DisplayRequestLoadRequestDownloadRequest 三种,他们又都有不同的 ImageResult 实现,因此 Target 也有对应的三种实现:

下面演示创建自定义 DisplayTarget:

DisplayRequest(context, "https://www.example.com/image.jpg") {
    target(
        onStart = { placeholder: Drawable? ->
            // Handle the placeholder drawable. 
        },
        onSuccess = { result: Drawable ->
            // Handle the successful result Drawable. 
        },
        onError = { error: Drawable? ->
            // Handle the error drawable. 
        }
    )
}.enqueue(request)

LoadTarget 和 DownloadTarget 同 DisplayTarget 使用方式大同小异

DisplayTarget 通常用来将 Drawable 应用到 View,因此 Sketch 提供了 ViewDisplayTargetImageViewDisplayTarget 来简化使用

DisplayRequest 还提供了 target(ImageView) 方法来简化绑定到 ImageView,如下:

DisplayRequest(context, "https://www.example.com/image.jpg") {
    target(imageView)
}.enqueue()

RemoteViews

Sketch 提供了 RemoteViewsDisplayTarget 用来将图片显示到 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()

DisplayRequest(context, "https://www.example.com/image.jpg") {
    resize(100.dp2px, 100.dp2px, scale = START_CROP)
    target(
        RemoteViewsDisplayTarget(
            remoteViews = remoteViews,
            imageViewId = R.id.remoteViewsNotificationImage,
            ignoreNullDrawable = true,
            onUpdated = {
                val notificationManager =
                    context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                notificationManager.notify(1101, notification)
            }
        )
    )
}.enqueue()
  1. 如上所示 RemoteViewsDisplayTarget 仅将 Drawable 转换为 Bitmap 并调用 RemoteViews 的 setImageViewBitmap 方法设置 Bitmap
  2. 所以还需要你在 onUpdated 函数中刷新通知或 AppWidget 才能将 Bitmap 显示到屏幕上