2

Coil 接受可绘制资源作为错误占位符。有没有办法在这里使用图像 URL?

这是我正在处理的代码:

// Global variables
var currentlySelectedImageUri = mutableStateOf<Uri?>(null)
var previousImageUri: Uri? = null

// @Composable fun() {...
Image(
    painter = rememberImagePainter(
    if (currentlySelectedImageUri.value != null) { // use the currently selected image
        currentlySelectedImageUri.value
    } else {
        if (previousImageUri != null) { // use the previously selected image
            previousImageUri
        } else {
            R.drawable.blank_profile_picture // use the placeholder image
        }
    }, builder = {
        placeholder(R.drawable.blank_profile_picture)
        error(R.drawable.blank_profile_picture) // FIXME: Set the previously selected image
    }),
    contentDescription = "profile image",
    contentScale = ContentScale.Crop,
    modifier = Modifier.fillMaxWidth()
)
4

3 回答 3

4

您可以检查painter.state值。

最初它是ImagePainter.State.Empty,而图像正在加载它ImagePainter.State.Loading,如果它失败 - 它变成ImagePainter.State.Error. 此时您可以更改线圈 url,例如,使用本地记忆变量:

val localImagePainterUrl = remember { mutableStateOf<Uri?>(null) }
val painter = rememberImagePainter(
    data = localImagePainterUrl.value
        ?: currentlySelectedImageUri.value
        ?: previousImageUri
        ?: R.drawable.blank_profile_picture,
    builder = {
        placeholder(R.drawable.blank_profile_picture)
    })
val isError = painter.state is ImagePainter.State.Error
LaunchedEffect(isError) {
    if (isError) {
        localImagePainterUrl.value = previousImageUri
    }
}

Image(
    painter = painter,
    ...
)
于 2021-08-10T13:26:09.837 回答
2

实际上有一个更简单的方法来自线圈 compose api,您只需将 error(R.drawable.your_placeholder_drawable) 添加到构建器即可

Image(painter = rememberImagePainter(data = url, builder = {error(R.drawable.your_placeholder_drawable)}))

于 2021-12-14T18:52:43.017 回答
1

线圈 ImageRequest Builder 类里面有一个函数

  fun placeholder(@DrawableRes drawableResId: Int) = apply {
      this.placeholderResId = drawableResId
      this.placeholderDrawable = null
  }

用法:

Image(
        painter = rememberImagePainter(
            data = url,
            builder = {
                placeholder(R.drawable.your_placeholder_drawable) // or bitmap
            }
        )
    )

更新

也可以使用:com.google.accompanist.placeholder

依赖等级:com.google.accompanist:accompanist-placeholder:accompanist_version

// accompanist_version = 0.19.0

Modifier.placeholder(
        visible =  true/false,
        color = color,
        highlight = PlaceholderHighlight.shimmer(color),
        shape = imageShape // RectangleShape)
于 2021-08-10T15:20:09.960 回答