如何使用 Picasso 库加载远程 svg 文件

Fra*_*odo 4 android picasso

我正在构建一个需要从服务器下载 svg 图像的 android 应用程序。我曾尝试以通常的方式使用毕加索,但它什么也没显示。

Picasso.get().load(url).into(imageView)
Run Code Online (Sandbox Code Playgroud)

有没有办法用毕加索显示矢量图像?

Ami*_*ome 8

您可以使用名为GlideToVectorYou的库,它在内部使用 Glide。

fun ImageView.loadSvg(url: String?) {
    GlideToVectorYou
        .init()
        .with(this.context)
        .setPlaceHolder(R.drawable.loading, R.drawable.actual)
        .load(Uri.parse(url), this)
}
Run Code Online (Sandbox Code Playgroud)

或者您也可以使用 Coil 库来加载 svg。只需在 build.gradle 中添加这些行

// ... Coil (https://github.com/coil-kt/coil)
implementation("io.coil-kt:coil:0.12.0")
implementation("io.coil-kt:coil-svg:0.12.0")
Run Code Online (Sandbox Code Playgroud)

然后添加扩展功能

fun AppCompatImageView.loadSvg(url: String) {
    val imageLoader = ImageLoader.Builder(this.context)
        .componentRegistry { add(SvgDecoder(this@loadSvg.context)) }
        .build()

    val request = ImageRequest.Builder(this.context)
        .crossfade(true)
        .crossfade(500)
        .data(url)
        .target(this)
        .build()

    imageLoader.enqueue(request)
}
Run Code Online (Sandbox Code Playgroud)

然后在您的活动或片段中调用此方法

your_image_view.loadSvg("your_file_name.svg")
Run Code Online (Sandbox Code Playgroud)

  • 根据问题,这是关于毕加索库的,不是任何可能的方式,所以我认为你的答案超出了主题。有时,无法仅针对单个用例更改主图像加载库,我们绝对不应该为其添加另一个库! (2认同)