Awe*_*eda 8 java xcode android ios swift
我有一个 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 字符串绕过它。
接受的答案并没有真正帮助我,因为 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'
Run Code Online (Sandbox Code Playgroud)
代码片段
//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)
Run Code Online (Sandbox Code Playgroud)
如果您不想使用Glide,而是想直接将SVG图像设置为ImageView,请执行以下操作:
yourImageView.setImageDrawable(drawable);
Run Code Online (Sandbox Code Playgroud)
试试这个,我想这可能对你有帮助。让我知道这是否有效
String yourSvgFile = "Your svg file";
InputStream stream = new ByteArrayInputStream(yourSvgFile.getBytes(StandardCharsets.UTF_8));
Glide.with(this).load(stream).into(yourView)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3554 次 |
| 最近记录: |