使用线圈加载图像时添加微光并进行构图

svg*_*svg 6 android kotlin android-jetpack-compose coil

从 Web URL 加载图像并在加载过程中显示闪烁效果。有没有更好的方法来处理这个问题?

val context = LocalContext.current
val imageLoader = ImageLoader(context)

val request = ImageRequest.Builder(context)
        .data(thumbnailUrl)
        .build()

val painter = rememberImagePainter(
        request = request,
        imageLoader = imageLoader
    )

val state = painter.state

Image(
  painter = painter,
  contentDescription = "thumbnail image",
  modifier = Modifier
            .fillMaxSize()
            .placeholder(
                visible = state is 
  ImagePainter.State.Loading,
                color = PlaceholderDefaults.color(
                    backgroundColor = MyTheme.colors.shimmer.copy(0.1f),
                ),
                highlight = PlaceholderHighlight.shimmer(),
            ),
        contentScale = ContentScale.Crop
    )
Run Code Online (Sandbox Code Playgroud)

您将如何向此请求添加令牌?我尝试使用令牌设置标头但没有响应。有什么建议么?

Atu*_*rma -1

只需执行以下几个步骤,Google 伴奏库就可以非常轻松地实现。

步骤 1.build.gradle首先,通过更改相应文件来设置要使用的库:

repositories {
    mavenCentral()
}

dependencies {
    // If you're using Material, use accompanist-placeholder-material
    implementation "com.google.accompanist:accompanist-placeholder-material:0.32.0"

    // Otherwise use the foundation version
    implementation "com.google.accompanist:accompanist-placeholder:0.32.0"
}
Run Code Online (Sandbox Code Playgroud)

步骤2.然后您可以使用修饰符来使用该功能。对于微光,您可以按照以下代码操作:

import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.material.placeholder
import com.google.accompanist.placeholder.material.shimmer

YourComposableHere(
    modifier = Modifier
        .placeholder(
            visible = true,
            highlight = PlaceholderHighlight.shimmer(),
        ),
    //...
) {
    // Body if any...
}
Run Code Online (Sandbox Code Playgroud)

您还可以在以下位置查看最新版本和文档(参考): https: //google.github.io/accompanist/placeholder/

现在,我们只需更改 的isVisible参数即可.placeholder()根据图像加载状态显示和隐藏微光,就像您在问题中所做的那样。

有没有更好的方法来处理这个问题?

它非常简单干净,所以我认为这是目前最好的方法。