【问题标题】:android:load svg file from web and show it on image viewandroid:load svg file from web and show it on image view
【发布时间】:2015-03-28 17:34:55
【问题描述】:

我想从网上加载一个 svg 文件并在 ImageView 中显示这个文件。对于非矢量图像,我使用Picasso 库。

是否也可以将此库用于 svg 文件?
有没有办法从网络加载 svg 文件并将其显示在 ImageView 中?
我使用svg-android 库来显示 svg 文件,但我不知道如何从网络获取 svg 图像,该库的所有示例都使用本地文件。

【问题讨论】:

  • " 有没有办法从 web 加载 svg 文件并在图像视图中显示它?" -- 使用HttpUrlConnection、HttpClient、OkHttp、Volley、Ion 或任何数量的其他 HTTP 客户端库。

标签: android svg imageview picasso svg-android


【解决方案1】:

请参考Having issue on Real Device using vector image in android. SVG-android

在用户帖子中,他提出了类似的问题并建议他使用:

在布局文件中为 ImageView 创建一个成员变量;

private ImageView mImageView;

// intialize in onCreate(Bundle savedInstanceState)
mImageView = (ImageView) findViewById(R.id.image_view);

下载图片

private class HttpImageRequestTask extends AsyncTask<Void, Void, Drawable> {
    @Override
    protected Drawable doInBackground(Void... params) {
        try {


            final URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/e/e8/Svg_example3.svg");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            SVG svg = SVGParser. getSVGFromInputStream(inputStream);
            Drawable drawable = svg.createPictureDrawable();
            return drawable;
        } catch (Exception e) {
            Log.e("MainActivity", e.getMessage(), e);
        }

        return null;
    }

    @Override
    protected void onPostExecute(Drawable drawable) {
        // Update the view
        updateImageView(drawable);
    }
}

然后将drawable应用到Imageview

@SuppressLint("NewApi")
private void updateImageView(Drawable drawable){
    if(drawable != null){

        // Try using your library and adding this layer type before switching your SVG parsing
        mImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        mImageView.setImageDrawable(drawable);
    }
}

SVGParser 可通过https://github.com/pents90/svg-android获得

【讨论】:

  • 它返回给我这个错误:com.larvalabs.svgandroid.SVGParseException: org.xml.sax.SAXException: 没有指定输入。对于这一行:SVG svg = SVGParser.getSVGFromInputStream(inputStream);
  • 是的。此方法需要返回 XML,并且我使用的是 .svg 文件。因此,我将使用有效的 XML 源更新我的答案。抱歉耽搁了
  • @mahdi 请查看实际可以引用 .svg 或 .xml 文件的更新答案。这是因为 .svg 确实包含 xml
  • 出现错误 org.apache.harmony.xml.ExpatParser$ParseException:在第 1 行,第 0 列:在此行中找不到元素 SVG svg = SVGParser.getSVGFromInputStream(inputStream);
  • @AshishPatel 请参阅code.google.com/archive/p/svg-android 这是 OP 的问题,因为它是他正在使用的库
【解决方案2】:

更新:如需更新版本,请查看 Glide 示例 (https://github.com/bumptech/glide/tree/master/samples/svg)

-

您可以使用 Glide (https://github.com/bumptech/glide/tree/v3.6.0) 和 AndroidSVG (https://bitbucket.org/paullebeau/androidsvg)。

还有一个来自 Glide 的示例:https://github.com/bumptech/glide/tree/v3.6.0/samples/svg/src/main/java/com/bumptech/svgsample/app

设置 GenericRequestBuilder

requestBuilder = Glide.with(mActivity)
    .using(Glide.buildStreamModelLoader(Uri.class, mActivity), InputStream.class)
            .from(Uri.class)
            .as(SVG.class)
            .transcode(new SvgDrawableTranscoder(), PictureDrawable.class)
            .sourceEncoder(new StreamEncoder())
            .cacheDecoder(new FileToStreamDecoder<SVG>(new SvgDecoder()))
            .decoder(new SvgDecoder())
                    .placeholder(R.drawable.ic_facebook)
                    .error(R.drawable.ic_web)
            .animate(android.R.anim.fade_in)
            .listener(new SvgSoftwareLayerSetter<Uri>());

将 RequestBuilder 与 uri 一起使用

Uri uri = Uri.parse("https://de.wikipedia.org/wiki/Scalable_Vector_Graphics#/media/File:SVG_logo.svg");
            requestBuilder
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                            // SVG cannot be serialized so it's not worth to cache it
                    .load(uri)
                    .into(mImageView);

【讨论】:

  • 你先生,拯救了我的一天:D
  • 什么是requestBuilder?什么是 SvgDrawableTranscoder?什么是 SvgDecoder?什么是 SvgDecoder?什么是 SvgSoftwareLayerSetter?
  • 请查看 Glide 的示例:github.com/bumptech/glide/tree/v3.6.0/samples/svg/src/main/java/… Requestbuilder 是 Glide 的“GenericRequestBuilder” (bumptech.github.io/glide/javadocs/latest/index.html) SVGDrawableTranscoder、SVGDecoder 和 SVGSoftwareLayerSetter 是扩展 Glide 以在帮助下加载和显示 SVG 的类AndroidSVG 的。
  • glide 3.6.0 的好例子,但我不知道如何在 4.0.0 上做到这一点。顺便说一句,如果你可以降级到 3.6.0(就像我在我的项目中所做的那样)它的工作原理很完美!
  • 我用的是glide 4.9.0,有很多变化。你有最新的例子吗?
【解决方案3】:

使用这个Glide based library加载xml

添加依赖

  compile 'com.github.ar-android:AndroidSvgLoader:1.0.0'

对于最新的 android 依赖 Gradle,请改用它

implementation 'com.github.ar-android:AndroidSvgLoader:1.0.0'

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/ivimage"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_item);            

        ImageView image = (ImageView) findViewById(R.id.ivimage);

        SvgLoader.pluck()
                .with(this)
                .setPlaceHolder(R.mipmap.ic_launcher, R.mipmap.ic_launcher)
                .load("http://www.clker.com/cliparts/u/Z/2/b/a/6/android-toy-h.svg", image);

    }

    @Override protected void onDestroy() {
        super.onDestroy();
        SvgLoader.pluck().close();
    }
}

【讨论】:

  • Glide 有一个非常烦人的许可证(我在一段时间内看到的更令人困惑的许可证之一)如果有一个不需要我在我的应用程序中提供许可证文档的解决方案会很高兴。跨度>
  • 在项目 build.gradle 文件中也包含这个: allprojects { repositories { maven { url 'jitpack.io' } } }
  • 这个库给了我这个错误:程序类型已经存在:com.caverock.androidsvg.CSSParser$Attrib
【解决方案4】:

你可以使用这个库

https://github.com/2coffees1team/GlideToVectorYou

正如他所说:“该库基于 Glide 并提供相同的功能 + svg 支持”。

【讨论】:

    【解决方案5】:

    希望下面的代码对你有用。

    1. build.gradle

      中添加这个依赖

      implementation 'com.github.corouteam:GlideToVectorYou:v2.0.0'

    2. 现在开始在 MainActivity.java

      中工作

      ImageView image = (ImageView) findViewById(R.id.ivimage);

      String url= https://your_url/banking.svg GlideToVectorYou.init().with(this).load(Uri.parse(url),image);

    【讨论】:

    • 这太好了,谢谢!请注意 - 同样在项目级别的 gradle 文件中,需要添加:maven { url 'https://jitpack.io' },在 repositories
    【解决方案6】:

    Kotlin 和线圈库从 URL 加载 SVG:

    1. 在 build.gradle 中添加 Kotlin 图片加载库(模块:app)(也支持其他图片):

    分级:

    implementation 'io.coil-kt:coil:1.4.0'
    implementation 'io.coil-kt:coil-svg:1.4.0'
    

    Kts:

    implementation("io.coil-kt:coil:1.4.0")
    implementation("io.coil-kt:coil-svg:1.4.0")
    
    1. 将以下扩展功能添加到项目的任何 Kotlin 文件中, (类外而不是类内):

    这里我在 xml 中使用了 AppCompatImageView,如果你只使用 ImageView,请从下面的函数中用 ImageView 替换 AppCompatImageView。

    fun AppCompatImageView.loadSvgOrOther(myUrl: String?, cache: Boolean = true, errorImg: Int = R.drawable.logo_round // Place any error image from your drawable) {
    
    myUrl?.let {
        if (it.lowercase().endsWith("svg")) {
            val imageLoader = ImageLoader.Builder(this.context)
                .componentRegistry {
                    add(SvgDecoder(this@loadSvgOrOther.context))
                }.build()
    
            val request = ImageRequest.Builder(this.context).apply {
                error(errorImg)
                placeholder(errorImg)
                data(it).decoder(SvgDecoder(this@loadSvgOrOther.context))
            }.target(this).build()
    
            imageLoader.enqueue(request)
        } else {
            val imageLoader = ImageLoader(context)
    
            val request = ImageRequest.Builder(context).apply {
                if (cache) {
                    memoryCachePolicy(CachePolicy.ENABLED)
                } else {
                    memoryCachePolicy(CachePolicy.DISABLED)
                }
                error(errorImg)
                placeholder(errorImg)
                data("$it")
            }.target(this).build()
    
            imageLoader.enqueue(request)
        }
      }
    } // loadSvgOrOther
    
    1. 现在使用如下:

      myAppCompatImageView.loadSvgOrOther("https[:]//example[.]com/image.svg")
      

    希望这对想要使用 Kotlin 加载 svg、png、jpg 等图像的人有所帮助。

    【讨论】:

    • 在我的情况下找不到 SvgDecoder 类。你能帮我调用它的过程吗
    • @AminulHaqueAome 还在 gradle 中添加这一行: implementation("io.coil-kt:coil-svg:0.11.0") (答案已更新)
    • 是的,我也试过了。但问题是,线圈和线圈 svg 的版本之间存在冲突。也许我今天可以解决这个问题。并感谢您的回复vai
    • vai,另一个问题。如何在此方法中使用 placeHolder?
    • @Touhid imageLoader.execute(request) 出错并说函数必须暂停。为什么?? .为什么 LoadRequest 是未知的??
    【解决方案7】:

    使用 Glide V4 或更高版本加载 SVG

    在app.gradle中添加依赖>依赖

    implementation 'com.github.qoqa:glide-svg:2.0.4'
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
    

    新建类 SampleAppGlideModule.java 并转到 Build>Make Project(ctrl+f9)

    import android.content.Context;
    import android.util.Log;
    
    import androidx.annotation.NonNull;
    
    import com.bumptech.glide.GlideBuilder;
    import com.bumptech.glide.annotation.GlideModule;
    import com.bumptech.glide.module.AppGlideModule;
    
    @GlideModule
    public class SampleAppGlideModule extends AppGlideModule {
    
    
    
        @Override
        public boolean isManifestParsingEnabled() {
            return super.isManifestParsingEnabled();
        }
    
        @Override
        public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
            super.applyOptions(context, builder);
            builder.setLogLevel(Log.DEBUG);
        }
    }
    

    使用 Glide V4 或更高版本加载 SVG

    GlideApp.with(this)                      
    .load(contentLangModels.get(i).getContentImage()).into(contentLangBinding.ivExtra);
    

    【讨论】:

      【解决方案8】:

      您可以使用线圈图像加载库,

      将以下依赖项添加到您的应用级 build.gradle 文件中,

      def coilVersion = '1.2.2'
      implementation "io.coil-kt:coil:$coilVersion"
      implementation "io.coil-kt:coil-svg:$coilVersion"
      

      现在创建这个方法,

      fun ImageView.loadImageFromUrl(imageUrl: String) {
      val imageLoader = ImageLoader.Builder(this.context)
          .componentRegistry { add(SvgDecoder(this@loadImageFromUrl.context)) 
      }
          .build()
      
      val imageRequest = ImageRequest.Builder(this.context)
          .crossfade(true)
          .crossfade(300)
          .data(imageUrl)
          .target(
              onStart = {
                  //set up an image loader or whatever you need
              },
              onSuccess = { result ->
                  val bitmap = (result as BitmapDrawable).bitmap
                  this.setImageBitmap(bitmap)
                  //dismiss the loader if any
              },
              onError = {
                  /**
                   * TODO: set an error drawable
                   */
              }
          )
          .build()
      
      imageLoader.enqueue(imageRequest)
      

      }

      现在你可以从你的 ImageView 调用这个扩展函数了,

      imgView.loadImage(imageUrl)
      

      这适用于 svg、png。我还没有尝试过使用 jpg,但也应该使用它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-01
        • 2022-12-02
        • 1970-01-01
        • 2022-12-02
        • 2022-12-28
        • 2013-08-25
        • 1970-01-01
        • 2022-12-01
        相关资源
        最近更新 更多