如何将SVG字符串加载到ImageView中

8

我有一个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中使用Glide或其他SVG库加载它,但不知道如何处理这个SVG字符串。


如果想使用SVG文件,必须使用矢量图形。 - mostafa tayebi
寻找支持字符串的SVG库。或者,将字符串写入文件,然后使用SVG库。 - CommonsWare
1
最终找到一个库 https://bigbadaboom.github.io/androidsvg/api_summary_11.html,它支持从字符串加载SVG。 - Aweda
2个回答

6

采纳的答案并没有真正帮助我,因为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'

代码片段

//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);

1
这个有效了,而被接受的答案却没有。 - htafoya
1
正在使用AndroidSVG的人请注意,我尝试了将Bitmap转换为Canvas再使用AndroidSVGObj.renderToCanvas的方法,但它没有起作用。但上述方法有效。对这个答案点赞。 - nayakasu

4

试一下这个,我认为这可能会对你有所帮助。如果有效,请告诉我。

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

不,我是从 API 中获取 SVG 字符串,而不是从 .svg 文件中获取。 - Aweda
2
用 API 响应中的字符串替换 "your svg 文件" - Arunachalam k
似乎无法工作:´val stream = svg.byteInputStream(StandardCharsets.UTF_8) Glide.with(this).load(stream).into(binding.img)´ - htafoya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接