android - 在 Android 中使用 SVG 作为背景可绘制对象

标签 android background svg

我正在尝试使用 SVG 图像(使用 Inkscape 创建并保存为纯 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 有问题。这可能是因为不支持所有功能。

最佳答案

svg-android 项目已经一年多没有更新了,它不支持 SVG1.2,所以不支持 Inkscape(开源)生成的 svgs。

但是有一个新的 android svg 库:AndroidSVG

它们的版本是 1.2,1.3 的工作目前正在进行中。仅包括 jar 库,您可以通过编程方式将 svgs 包含在 android 应用程序中。几乎包含所有 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 放入 Assets 文件夹中,一切顺利。

它支持 API 8 及更高版本。将它用于 API < 11 时出现了一些问题,但我能够解决这些问题。我将它们作为问题发布在项目页面上,作者在几分钟内做出了回应。它们已添加到下一个修订版中。如果您有任何问题,请查看已解决的问题,否则我可以在这里回答问题。

附言项目页面上的文档和示例非常好,使用该库很愉快。 Android 和 svg 是一个强大的组合。

关于android - 在 Android 中使用 SVG 作为背景可绘制对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7862493/

相关文章:

html - 如何在 SVG 矩形中添加选择器之前或之后?

安卓.view.InflateException : Binary XML file line #13: Error inflating class fragment

android - AIR 参数错误 : Error #2004: - Android

java - 静态变量未正确返回?

background - 设置背景图片xcode6

iphone - MPMusicPlayerController 在后台暂停并在应用程序进入前台时恢复

javascript - 使用SVG在html页面中显示动态圆

java - 在Android studio 3.2中查找Sqlite数据库

image - IE10 的背景图像和渐变

PHP Imagick 无法读取 SVG 文件