简体   繁体   English

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

[英]How to load remote svg files with Picasso library

I'm building an android app that requires downloading svg images from a server.我正在构建一个需要从服务器下载 svg 图像的 android 应用程序。 I have tried using Picasso the usual way but it displays nothing.我曾尝试以通常的方式使用毕加索,但它什么也没显示。

Picasso.get().load(url).into(imageView)

Is there anyway to display vector images with Picasso?有没有办法用毕加索显示矢量图像?

You can use a library called GlideToVectorYou which uses Glide internally.您可以使用名为GlideToVectorYou的库,它在内部使用 Glide。

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

or You can also use Coil library to load svg.或者您也可以使用 Coil 库来加载 svg。 Just add these lines in build.gradle只需在 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")

Then Add an extension function然后添加扩展功能

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)
}

Then call this method in your activity or fragment然后在您的活动或片段中调用此方法

your_image_view.loadSvg("your_file_name.svg")

My advice, try to move to Glide library.我的建议是,尝试转移到 Glide 库。 Under hood, lib could load svg and much more things.在引擎盖下,lib 可以加载 svg 和更多东西。 Here is an examples . 这是一个例子

use coil in kotlin for handle svg files在 kotlin 中使用线圈处理 svg 文件

first add首先添加

// Coil
implementation "io.coil-kt:coil-compose:1.3.2"
implementation "io.coil-kt:coil-svg:1.3.2"

then use然后使用

fun ImageView.loadImage(imageUri: String, placeholder: Int? = null) {

val imageLoader = ImageLoader.Builder(this.context)
    .componentRegistry { add(SvgDecoder(this@loadImage.context)) }
    .build()

load(uri = imageUri, imageLoader = imageLoader) {
           crossfade(true)
           placeholder(placeholder ?: R.drawable.image_avatar)
       }
   }

使用扩展函数对 anwer 进行补充,如果您在 xml 中仅使用 ImageView,请从函数中将 AppCompatImageView 替换为 ImageView。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM