在Android中使用SVG作为背景可绘制资源

17

我想把一个使用Inkscape创建并以普通SVG格式保存的SVG图像作为我的应用程序的背景。我正在尝试使用svg-android库来实现这一点。我在res/raw中有一个名为background.svg的文件。我的代码如下:

SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.background);
Drawable pictureDrawable = svg.createPictureDrawable();
Bitmap bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(), pictureDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);

LinearLayout backgroundLayout = (LinearLayout) findViewById(R.id.background);
bitmapDrawable.setTileModeX(Shader.TileMode.REPEAT);
backgroundLayout.setBackgroundDrawable(bitmapDrawable);

然而,当我的应用程序启动时,除了布局的背景颜色之外,没有任何内容显示为背景。我的布局xml文件如下:

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

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/background"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    >
 </LinearLayout>

</LinearLayout>

更新

看起来我的SVG存在问题。可能是因为并不支持所有的功能。


你尝试过将Drawable的pictureDrawable设置为布局的背景,而不是BitmapDrawable的bitmapDrawable吗? - Dimitris Makris
@DimitrisMakris 是的,那是我尝试的第一件事,但我仍然得到了一个空白背景。另一个问题是没有办法在PictureDrawable上设置平铺。 - Vivin Paliath
以防万一; 你知道安卓不支持SVG原生。 在安卓上试试你的代码,用火狐浏览器? - Chasbeen
是的,虽然不是本地支持,但svg-android库可以帮助您在Android上处理SVG。 - Vivin Paliath
2个回答

19

svg-android项目已经超过一年没有更新,不支持SVG1.2,因此不支持由Inkscape(开源)生成的SVG。

然而,现在有一个新的android svg库:AndroidSVG

它们目前处于1.2版本,并且正在进行1.3版本的开发。只需包含jar库,就可以在android应用程序中以编程方式包含svg。几乎所有的svg功能都包含在内。我尚未找到任何无法使用该库合并的svg。

如果将androidsvg作为库模块从源代码(hg clone)中包含到您的项目中,则可以获得SVGImageView类,它是ImageView的扩展,您可以像下面这样使用xml布局文件向您的项目添加svg:

<com.caverock.androidsvg.SVGImageView
    xmlns:svg="http://schemas.android.com/apk/res-auto"
    android:layout_width="100dp"
    android:layout_height="50dp"
    svg:svg="filename.svg"/>

好了,你只需要把filename.svg放在资产文件夹中就可以了。

它支持API 8及以上版本。使用API < 11时有一些问题,但我已经解决了。我在项目页面上发布了这些问题,并且作者在几分钟内回应了。这些问题已经添加到下一个版本中。如果您遇到任何问题,请查看已解决的问题,如果仍然有问题,我可以在这里回答。

P.S. 项目页面上的文档和示例非常好,这个库使用起来很方便。Android和svg是一个强大的组合。


1

我尝试了使用以下代码的示例,它正确显示了背景:

LinearLayout root = (LinearLayout) findViewById(R.id.background);
SVG svg = SVGParser.getSVGFromResource(getResources(),
                R.raw.android_body);
Drawable pictureDrawable = svg.createPictureDrawable();
root.setBackgroundDrawable(pictureDrawable);

你尝试过使用另一个SVG吗?


我尝试在浏览器中加载SVG,它似乎显示正常,所以看起来没有任何问题。让我再试另一个SVG。哦,还有,你是否尝试过像我这样嵌套布局的方式?我想知道这是否会导致问题。 - Vivin Paliath
是的,完全相同的布局,但是这不相关。我使用的SVG来自svg-android项目(即动态壁纸项目)。 - Dimitris Makris
我使用他们提供的SVG尝试了一下,似乎可以工作。所以我猜这是我的SVG出了问题。 - Vivin Paliath

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