2011-10-22 124 views
11

我想使用SVG图像(使用Inkscape创建并保存为纯SVG)作为我的应用程序的背景。我正在尝试使用svg-android库来做到这一点。我在res/raw有一个名为background.svg的文件。我的代码如下所示:在Android中使用SVG作为背景drawable

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> 

UPDATE

看来,有一个与我的SVG的一个问题。这可能是由于所有功能都不受支持。

+0

您是否尝试将可绘制的pictureDrawable设置为布局的背景而不是BitmapDrawable bitmapDrawable? –

+0

@DimitrisMakris是的,那是我尝试的第一件事,但我仍然留有空白背景。另一个问题是,无法在“PictureDrawable”上设置拼贴。 –

+0

以防万一; - ü知道android本身不支持SVG 在Android上使用firefox试试你的代码? – Chasbeen

回答

14

svg-android项目在一年内还没有更新,它不支持SVG1.2,因此不支持Inkscape(开源)生成的svgs。

然而,有一个新的Android SVG库:AndroidSVG

他们是在1.2版本和工作在1.3是目前正在进行中。只包括jar库,可以编程方式在android应用程序中包含svgs。几乎所有的svg功能都包含在内。我还没有找到一个我无法使用这个库合并的svg。

如果包括从源(HG克隆)在您的项目androidsvg为库模块,你得到的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用于API <时有几个问题,但我能够解决这些问题。我将它们作为问题发布在项目页面上,作者在几分钟内回复。他们已被添加到下一个版本。如果您遇到任何问题,请查看解决的问题,否则我可以在此处回答问题。

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?

+0

我曾尝试在浏览器中加载SVG,它似乎显示正常,所以它看起来不像它有任何问题。让我试试另一个svg。哦,你是否也尝试过像我拥有它一样的嵌套布局?我想知道这是否有助于解决问题。 –

+0

Yeap,exaclty相同的布局,但是这是无关紧要的。我使用SVG是从SVG-Android项目(动态壁纸项目) –

+0

我与他们所提供的SVG尝试过了,它似乎工作。所以我想这是我的svg的问题。 –