【问题标题】:How do I load SVG String into ImageView如何将 SVG 字符串加载到 ImageView
【发布时间】:2019-12-22 13:06:59
【问题描述】:

我有一个 SVG 字符串

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 30" width="1200" height="600"><clipPath id="a"><path d="M30 15h30v15zv15h-30zh-30v-15zv-15h30z"/></clipPath><path d="M0 0v30h60v-30z" fill="#00247d"/><path d="M0 0l60 30m0-30l-60 30" stroke="#fff" stroke-width="6"/><path d="M0 0l60 30m0-30l-60 30" clip-path="url(#a)" stroke="#cf142b" stroke-width="4"/><path d="M30 0v30m-30-15h60" stroke="#fff" stroke-width="10"/><path d="M30 0v30m-30-15h60" stroke="#cf142b" stroke-width="6"/></svg>

如何在 ImageView 上渲染它?

如果这是 .svg 文件,我可以在 Android 或其他 SVG 库中使用 Glide 加载它,但不知道如何使用这个 svg 字符串绕过它。

【问题讨论】:

  • 如果你想使用SVG文件,你必须使用vector drawable。
  • 查找支持字符串的 SVG 库。或者,将字符串写入文件,然后使用 SVG 库。
  • 终于找到了一个库bigbadaboom.github.io/androidsvg/api_summary_11.html,支持从字符串加载SVG。

标签: java android ios swift xcode


【解决方案1】:

试试这个,我想这可能对你有帮助。让我知道这是否有效

 String yourSvgFile = "Your svg file";
        InputStream stream = new ByteArrayInputStream(yourSvgFile.getBytes(StandardCharsets.UTF_8));
        Glide.with(this).load(stream).into(yourView)

【讨论】:

  • 不,我从 API 获取 svg 字符串,而不是 .svg 文件。
  • 用来自 api 响应的字符串替换“你的 svg 文件”
【解决方案2】:

接受的答案并没有真正帮助我,因为 Glide 抛出了一个异常,要求为 ByteArrayInputStream 类型创建一个 ModelLoader。添加到@Aweda 的答案中,我使用了 AndroidSVG 库,如下所示。

依赖关系

//AndroidSVG
implementation 'com.caverock:androidsvg-aar:1.4'

//Glide (add only if you're going to use Glide to load the  image)
implementation 'com.github.bumptech.glide:glide:4.12.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'

代码sn-p

//SVG string content 
 val svgString =
            "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 60 30\" width=\"1200\" height=\"600\"><clipPath id=\"a\"><path d=\"M30 15h30v15zv15h-30zh-30v-15zv-15h30z\"/></clipPath><path d=\"M0 0v30h60v-30z\" fill=\"#00247d\"/><path d=\"M0 0l60 30m0-30l-60 30\" stroke=\"#fff\" stroke-width=\"6\"/><path d=\"M0 0l60 30m0-30l-60 30\" clip-path=\"url(#a)\" stroke=\"#cf142b\" stroke-width=\"4\"/><path d=\"M30 0v30m-30-15h60\" stroke=\"#fff\" stroke-width=\"10\"/><path d=\"M30 0v30m-30-15h60\" stroke=\"#cf142b\" stroke-width=\"6\"/></svg>"

//convert SVG string to an object of type SVG
val svg = SVG.getFromString(svgString)

//create a drawable from svg
val drawable = PictureDrawable(svg.renderToPicture())

//finally load the drawable with Glide.
Glide.with(this)
            .load(drawable)
            .into(yourImageView)

如果你不想使用 Glide 并且想直接将 SVG 图像设置为 ImageView,请执行以下操作:

yourImageView.setImageDrawable(drawable);

【讨论】:

    猜你喜欢
    • 2023-02-17
    • 2020-06-06
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2021-06-24
    • 2017-05-19
    相关资源
    最近更新 更多