在Android上使用SVG图标的最佳做法是什么?

时间:2020-12-24 20:03:56

I am about to create my first Android native (so not browser based) app and looking for some good practices regarding icon creating/provisioning. Since it should support multiple devices/resolutions I thought it is best to use SVG to create them. There is at least this lib: http://code.google.com/p/svg-android/ that promises to offer support for SVG on Android.

我即将创建我的第一个Android原生(因此不是基于浏览器的)应用程序,并寻找有关图标创建/配置的一些好的做法。由于它应该支持多个设备/分辨率,我认为最好使用SVG来创建它们。至少有这个lib:http://code.google.com/p/svg-android/,它承诺在Android上提供对SVG的支持。

So far, I have not found resources describing the usage of this or another library as a means to render SVG Icons on the device, so I am a bit reluctant in using it. The best I have seen so far is using SVG as the source format for pre-rendering png based icons in different resolutions.

到目前为止,我还没有找到描述这个或另一个库的使用的资源作为在设备上呈现SVG图标的方法,所以我有点不情愿使用它。到目前为止,我见过的最好的是使用SVG作为预渲染基于png的图标在不同分辨率下的源格式。

So my questions is: Are SVG icons a good option to use directly on the device without a png pre-rendering step (does it work at all), and if, why does nobody seem to use this approach?

所以我的问题是:SVG图标是一个很好的选择,可以在没有png预渲染步骤的情况下直接在设备上使用(它是否可以工作),如果,为什么似乎没有人使用这种方法?

12 个解决方案

#1


25  

For Android older than Lollipop, your best practice for SVG on Android is going to be to use a tool to convert your SVG to PNG at the size(s) you're interested in. Existing SVG support for Android is not comprehensive of what you're likely to find in an SVG file, and even if it were, the support is not built into the OS so using them directly for icons is definitely out.

对于比Lollipop更早的Android,您在Android上使用SVG的最佳做法是使用工具将您的SVG转换为您感兴趣的大小的PNG。现有的Android SVG支持并不全面。 '很可能在SVG文件中找到,即使它是,但是操作系统没有内置支持,因此直接使用它们来获取图标肯定是不合适的。

Beginning with Lollipop (API 21) see What are best practices for using SVG icons on Android?. Thanks to @MarkWhitaker @AustynMahoney for pointing this out.

从Lollipop(API 21)开始,请参阅在Android上使用SVG图标的最佳做法是什么?感谢@MarkWhitaker @AustynMahoney指出这一点。

#2


39  

From Lollipop (API 21) onwards, Android defines the VectorDrawable class, for defining drawables based on vector graphics. Android Studio 1.4 adds the "Vector Asset Studio" to make them easier to work with, including an SVG import feature and a new Gradle plugin that generates PNG versions of VectorDrawable icons at build time for API 20 and earlier. There's also a third-party tool for converting SVGs to VectorDrawables. Bear in mind that although vector drawables can be defined in XML, the file format is not SVG and not all SVG files can be successfully converted. Simple graphics like icons should work OK.

从Lollipop(API 21)开始,Android定义了VectorDrawable类,用于根据矢量图形定义drawable。 Android Studio 1.4添加了“Vector Asset Studio”以使其更易于使用,包括SVG导入功能和新的Gradle插件,可在构建时为API 20及更早版本生成VectorGrawable图标的PNG版本。还有一个用于将SVG转换为VectorDrawables的第三方工具。请记住,尽管可以使用XML定义矢量drawable,但文件格式不是SVG,并且并非所有SVG文件都可以成功转换。像图标这样的简单图形应该可以。

If you still need to generate PNGs yourself, you'll need to generate your icons at various resolutions. For ease of generating those PNGs I design icons as SVG and then export to the various sizes using Inkscape which is free and cross-platform. It's got some nice features for designing icons, including the Icon Preview view (see below), and it generates nice crisp PNGs.

如果您仍然需要自己生成PNG,则需要以各种分辨率生成图标。为了便于生成这些PNG,我将图标设计为SVG,然后使用免费和跨平台的Inkscape导出为各种大小。它有一些很好的设计图标功能,包括图标预览视图(见下文),它可以生成漂亮的清晰PNG。

在Android上使用SVG图标的最佳做法是什么?

#3


31  

This is what we are using to transform a SVG file into multiple resolutions. For example, to generate the launch icon: svg2png -w48 icon.svg

这就是我们用来将SVG文件转换为多种分辨率的方法。例如,要生成启动图标:svg2png -w48 icon.svg

#!/bin/bash -e
# Transforms a SVG into a PNG for each platform
# Sizes extracted from
# http://developer.android.com/design/style/iconography.html

[ -z $2 ] && echo -e "ERROR: filename and one dimension (-w or -h) is required, for example:\nsvg2png -w48 icon.svg\n" && exit 1;
FILENAME=$2
DEST_FILENAME=`echo $2 | sed s/\.svg/\.png/`
FLAG=`echo $1 | cut -c1-2`
ORIGINAL_VALUE=`echo $1 | cut -c3-`

if [ "$FLAG" != "-w" ] && [ "$FLAG" != "-h" ]; then
    echo "Unknown parameter: $FLAG" 
    exit 1
fi

# PARAMETERS: {multiplier} {destination folder}
function export {
  VALUE=$(echo "scale=0; $ORIGINAL_VALUE*$1" | bc -l)
  CMD="inkscape $FLAG$VALUE --export-background-opacity=0 --export-png=src/main/res/$2/$DEST_FILENAME src/main/svg/$FILENAME > /dev/null"
  echo $CMD
  eval $CMD
} 

export 1 drawable-mdpi
export 1.5 drawable-hdpi
export 2 drawable-xhdpi
export 3 drawable-xxhdpi
export 4 drawable-xxxhdpi

#4


14  

Good news everyone! Since android support library 23.2 we can use svg-s till back to API level 7!

大家好消息!由于android支持库23.2我们可以使用svg-s直到回到API级别7!

If you wanna be compatible backwards only till Lollipop (API 21) check Mark Whitaker's answer, but if you want to go below you need to add these lines to your build.gradle:

如果你想向后兼容直到Lollipop(API 21)检查Mark Whitaker的答案,但如果你想要进入下面,你需要将这些行添加到你的build.gradle:

// Gradle Plugin 2.0+ (if you using older version check the library announcement link)
android {  
    defaultConfig {  
        vectorDrawables.useSupportLibrary = true  
    }  
}  

Also keep in mind that:

还要记住:

  • instead of android:src you need to use the app:srcCompat attribute in ImageViews.
  • 而不是android:src你需要在ImageViews中使用app:srcCompat属性。
  • you cannot use svg-s in StateListDrawables or other xml drawables, create them programmatically instead.
  • 你不能在StateListDrawables或其他xml drawables中使用svg-s,而是以编程方式创建它们。
  • you cannot use the android:background attribute or View.setBackgroundResource() function, use the View.setBackground() instead.
  • 你不能使用android:background属性或View.setBackgroundResource()函数,而是使用View.setBackground()。
  • you cannot use svg-s in case of Notifications.
  • 在通知的情况下,您不能使用svg-s。

#5


7  

Since nacho-coloma's answer helped me, I've taken his excellent script and made it slightly easier to use on a daily basis.

由于nacho-coloma的回答对我有所帮助,因此我采用了他出色的脚本,使其每天使用起来更容易一些。

First:

第一:

  1. Create directory drawable-svg next to your res directory.
  2. 在res目录旁边创建目录drawable-svg。
  3. Place your svg files and this script in drawable-svg.
  4. 将您的svg文件和此脚本放在drawable-svg中。
  5. Make the script executable.
  6. 使脚本可执行。
  7. Run it. In Ubuntu you can simply double-click it in Nautilus and make it run in a terminal.
  8. 运行。在Ubuntu中,您只需在Nautilus中双击它并使其在终端中运行即可。

And later when you get new svg files:

以后当你得到新的svg文件时:

  1. Place new svg files in drawable-svg and run the script again.
  2. 将新的svg文件放在drawable-svg中并再次运行该脚本。

By default it will do what you want: Scale every svg file into png files and put them into ../res/drawable-mdpi, ../res/drawable-hdpi etc.

默认情况下,它会执行您想要的操作:将每个svg文件扩展为png文件并将它们放入../res/drawable-mdpi,../res/drawable-hdpi等。

The script takes two parameters:

该脚本有两个参数:

  1. The svg file pattern to scale, default: *.svg
  2. 要扩展的svg文件模式,默认值:* .svg
  3. The base directory for put, default ../res/ (i.e. your res directory with the above mentioned setup).
  4. put的基本目录,默认为../res/(即具有上述设置的res目录)。

You can experiment by scaling a single svg into pngs in the current directory like this:

您可以通过将单个svg缩放到当前目录中的png来进行试验,如下所示:

$ ./svg2png test.svg .

Or simply process all images:

或者只是处理所有图像:

$ ./svg2png

I guess you could place the drawable-svg inside the res directory, but I haven't looked into what gets wrapped up in the final APK. Also, my svg files have - in their names, which Android doesn't like, and my script takes care of renaming the png files to something valid on Android.

我想你可以将drawable-svg放在res目录中,但我没有查看最终APK中包含的内容。此外,我的svg文件 - 在他们的名字中,Android不喜欢,并且我的脚本负责将png文件重命名为在Android上有效的东西。

I'm using ImageMagick for the conversion which is slightly more standard that Inkscape (though I liked the approach). Both methods are included in the script for reference.

我正在使用ImageMagick进行转换,这比Inkscape稍微标准一点(虽然我喜欢这种方法)。这两种方法都包含在脚本中以供参考。

Here's the script:

这是脚本:

#!/bin/bash

scalesvg ()
{
    svgfile="$1"
    pngdir="$2"
    pngscale="$3"
    qualifier="$4"

    svgwidthxheight=$(identify "$svgfile" | cut -d ' ' -f 3)
    svgwidth=${svgwidthxheight%x*}
    svgheight=${svgwidthxheight#*x}

    pngfile="$(basename $svgfile)" # Strip path.
    pngfile="${pngfile/.svg/.png}" # Replace extension.
    pngfile="${pngfile/[^A-Za-z0-9._]/_}" # Replace invalid characters.
    pngfile="$pngdir/$qualifier/$pngfile" # Prepend output path.

    if [ ! -d $(dirname "$pngfile") ]; then
        echo "WARNING: Output directory does not exist: $(dirname "$pngfile")"
        #echo "Exiting"
        #exit 1
        echo "Outputting here instead: $pngfile"
        pngfile="$qualifier-${svgfile/.svg/.png}"
    fi

    pngwidth=$(echo "scale=0; $svgwidth*$pngscale" | bc -l)
    pngheight=$(echo "scale=0; $svgheight*$pngscale" | bc -l)
    pngdensity=$(echo "scale=0; 72*$pngscale" | bc -l) # 72 is default, 

    echo "$svgfile ${svgwidth}×${svgheight}px -> $pngfile ${pngwidth}×${pngheight}px @ $pngdensity dpi"

    convert -background transparent -density $pngdensity "$svgfile" "$pngfile"
    #inkscape -w${pngwidth} --export-background-opacity=0 --export-png="$pngfile" "$svgfile" > /dev/null
    #convert "$svgfile" -background transparent -scale ${pngwidth}x${pngheight} "$pngfile"
}



svgfiles="$1"
svgfiles="${svgfiles:=*.svg}" # Default to input all *.svg in current dir.

pngdir="$2"
pngdir="${pngdir:=../res}" # Default to place output pngs to ../res, ie. ../res/drawable-hdpi etc.

for svgfile in $svgfiles; do
    echo "Scaling $svgfile ..."
    scalesvg "$svgfile" "$pngdir" 0.75 drawable-ldpi
    scalesvg "$svgfile" "$pngdir" 1    drawable-mdpi
    scalesvg "$svgfile" "$pngdir" 1.5  drawable-hdpi
    scalesvg "$svgfile" "$pngdir" 2    drawable-xhdpi
    scalesvg "$svgfile" "$pngdir" 3    drawable-xxhdpi
    scalesvg "$svgfile" "$pngdir" 4    drawable-xxxhdpi
done

echo -n "Done."
read # I've made it wait for Enter -- convenient when run from Nautilus.

#6


6  

Another option is to convert your SVG assets into TTF font type. Include the font on your app and use it that way. This does the trick for monochromatic simple shapes.

另一种选择是将SVG资产转换为TTF字体类型。在您的应用中包含该字体并以此方式使用它。这就是单色简单形状的技巧。

There are several free conversion tools.

有几种免费的转换工具。

#7


5  

Android Support Library 23.2 Support Vector Drawables and Animated Vector Drawables

Android支持库23.2支持矢量Drawables和动画矢量Drawables

  1. add vectorDrawables.useSupportLibrary = true to your build.gradle file.
  2. 将vectorDrawables.useSupportLibrary = true添加到build.gradle文件中。
  3. Use app:srcCompat="@drawable/ic_add" instead of android:src="..." or setImageResource() for your ImageView
  4. 使用app:srcCompat =“@ drawable / ic_add”而不是android:src =“...”或setImageResource()为您的ImageView

http://android-developers.blogspot.sk/2016/02/android-support-library-232.html

http://android-developers.blogspot.sk/2016/02/android-support-library-232.html

#8


3  

SVG icons are not a good option to use directly on a device if they need to be scaled to many different sizes, which is usually why you'd want to use vector format in the first place. A large icon will never scale down gracefully because, well, computer displays are made out of pixels. So the lines of the vector image may get aligned "in between pixels", creating a blurry border. Moreover, large icons need more details than small icons, which need very few details. A detailed icon does not look good in very small size, and a simple icon does not look good when scaled into very large size. I recently read an excellent article on this by a professional UI designer: About those vector icons.

SVG图标不是直接在设备上使用的好选项,如果它们需要缩放到许多不同的大小,这通常是你想要首先使用矢量格式的原因。大图标永远不会正常缩小,因为计算机显示器是由像素组成的。因此,矢量图像的线条可以“在像素之间”对齐,从而产生模糊的边界。此外,大图标需要比小图标更多的细节,小图标需要很少的细节。在非常小的尺寸中,详细的图标看起来不太好,当缩放到非常大的尺寸时,简单的图标看起来不太好。我最近阅读了一篇由专业UI设计师撰写的优秀文章:关于那些矢量图标。

#9


2  

I've just posted a script for generating all the platform icons for PhoneGap apps that may be of value. Yet to add code for generating screens.

我刚刚发布了一个脚本,用于生成可能有价值的PhoneGap应用程序的所有平台图标。然而,要添加用于生成屏幕的代码。

#10


2  

I've just started using Victor, an open source library by Trello, to convert SVG files to PNG files of the various required resolutions during build time.

我刚刚开始使用Trello的开源库Victor,在构建期间将SVG文件转换为各种所需分辨率的PNG文件。

PROS

PROS

  • You won't have to run a script or tool to create various PNG files every time you change or add an icon. (You do need to hit Rebuild in Android Studio when you've added a new svg file or renamed an existing one)
  • 每次更改或添加图标时,您都不必运行脚本或工具来创建各种PNG文件。 (当您添加新的svg文件或重命名现有文件时,您需要在Android Studio中点击Rebuild)
  • No PNG's in your source, so there's less clutter.
  • 您的来源中没有PNG,因此杂乱程度较低。

CONS

缺点

  • The only downside I've seen so far is that Android Studio doesn't yet recognize generated resources in XML, so you'll get some red warnings in your XML files and you don't have autocomplete for your SVG based drawables. It builds fine though, and this issue should be fixed in a future version of Android Studio.
  • 到目前为止我唯一看到的缺点是Android Studio尚未识别XML中生成的资源,因此您会在XML文件中收到一些红色警告,并且您没有基于SVG的drawable的自动完成功能。它构建得很好,这个问题应该在Android Studio的未来版本中修复。

If you use SVG generated by http://materialdesignicons.com/ be sure to either download the whole file, or copy from the 'SVG File'-tab when choosing 'View SVG'

如果您使用http://materialdesignicons.com/生成的SVG,请务必下载整个文件,或者在选择“查看SVG”时从“SVG文件”选项卡复制

#11


0  

I've never had much luck running Linux shell scripts in Cygwin on Windows. So here is a batch file that does what Nacho Coloma's bash script does. One small difference, is that this batch file requires both an input and an output file name, as in "svg2png -w24 input.svg output.png".

我在Windows上运行Cygwin中的Linux shell脚本时从来没有太多运气。所以这是一个批处理文件,它可以完成Nacho Coloma的bash脚本所做的工作。一个小的区别是,这个批处理文件需要输入和输出文件名,如“svg2png -w24 input.svg output.png”。

Set up an "svg" folder in your project's src/main directory and copy your SVG files and this batch file to that folder, per Stephan's instructions. Run the batch file from the svg folder. If you're on 32-bit Windows, then you will likely need to change the path to Inkscape to use "Program Files (x86)".

在项目的src / main目录中设置“svg”文件夹,并根据Stephan的说明将SVG文件和此批处理文件复制到该文件夹​​。从svg文件夹运行批处理文件。如果您使用的是32位Windows,则可能需要更改Inkscape的路径以使用“Program Files(x86)”。

@echo off
echo Convert an SVG file to a PNG resource file with multiple resolutions.

rem Check the arguments
set temp=%1
set switch=%temp:~0,2%
set pixels=%temp:~2%
if not "%switch%"=="-w" (
if not "%switch%"=="-h" (
echo Error:  Invalid image width or height switch.  Use -w or -h, with target image size in dp appended.
goto :error
))
echo %pixels%| findstr /r /c:"^[1-9][0-9]*$" >nul
if errorlevel 1 (
echo Error:  Invalid numeric image size.  Image size must be a positive integer.
goto :error
)
if "%3"=="" (
echo Error:  Not enough arguments.
goto :error
)
if not "%4"=="" (
echo Error:  Too many arguments.
goto :error
)

call :export %1 %2 %3 mdpi
call :export %1 %2 %3 hdpi
call :export %1 %2 %3 xhdpi
call :export %1 %2 %3 xxhdpi
call :export %1 %2 %3 xxxhdpi
exit /b

:export
rem parameters: <width/height> <input-file> <output-file> <density>

set temp=%1
set switch=%temp:~0,2%
set pixels=%temp:~2%

if %4==mdpi set /a size=%pixels%
if %4==hdpi set /a size=%pixels%*3/2
if %4==xhdpi set /a size=%pixels%*2
if %4==xxhdpi set /a size=%pixels%*3
if %4==xxxhdpi set /a size=%pixels%*4

echo %size% pixels ../res/drawable-%4/%3
"C:\Program Files\Inkscape\inkscape.exe" %switch%%size% --export-background-opacity=0 --export-png=../res/drawable-%4/%3 %2
exit /b

:error
echo Synopsis: svg2png -w^<width-pixels^>^|-h^<height-pixels^> ^<input-file^> ^<output-file^>
echo Example:  svg2png -w24 "wifi white.svg" wifi_connect_24dp.png
exit /b

#12


0  

svg is awesome. who want use svg:

svg太棒了。谁想要使用svg:

right click on drawable "new/Vector Asset" choose "material icon" for default icons and "locale SVG file" for your file in your computer hard drive and in "resource name" type name for svg file then click on "next" button and "finish"

右键单击drawable“new / Vector Asset”为您的计算机硬盘驱动器中的文件选择“material icon”作为默认图标和“locale SVG file”,在svg文件的“resource name”类型名称中单击“next”按钮和“完成”

and you can use that in drawable. fillcolor must be hard code.

你可以在drawable中使用它。 fillcolor必须是硬代码。

simple example

简单的例子

navigation_toggle.xml

navigation_toggle.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FFFFFF"
        android:pathData="M3,18h18v-2H3v2zm0,-5h18v-2H3v2zm0,-7v2h18V6H3z"/>
</vector>

#1


25  

For Android older than Lollipop, your best practice for SVG on Android is going to be to use a tool to convert your SVG to PNG at the size(s) you're interested in. Existing SVG support for Android is not comprehensive of what you're likely to find in an SVG file, and even if it were, the support is not built into the OS so using them directly for icons is definitely out.

对于比Lollipop更早的Android,您在Android上使用SVG的最佳做法是使用工具将您的SVG转换为您感兴趣的大小的PNG。现有的Android SVG支持并不全面。 '很可能在SVG文件中找到,即使它是,但是操作系统没有内置支持,因此直接使用它们来获取图标肯定是不合适的。

Beginning with Lollipop (API 21) see What are best practices for using SVG icons on Android?. Thanks to @MarkWhitaker @AustynMahoney for pointing this out.

从Lollipop(API 21)开始,请参阅在Android上使用SVG图标的最佳做法是什么?感谢@MarkWhitaker @AustynMahoney指出这一点。

#2


39  

From Lollipop (API 21) onwards, Android defines the VectorDrawable class, for defining drawables based on vector graphics. Android Studio 1.4 adds the "Vector Asset Studio" to make them easier to work with, including an SVG import feature and a new Gradle plugin that generates PNG versions of VectorDrawable icons at build time for API 20 and earlier. There's also a third-party tool for converting SVGs to VectorDrawables. Bear in mind that although vector drawables can be defined in XML, the file format is not SVG and not all SVG files can be successfully converted. Simple graphics like icons should work OK.

从Lollipop(API 21)开始,Android定义了VectorDrawable类,用于根据矢量图形定义drawable。 Android Studio 1.4添加了“Vector Asset Studio”以使其更易于使用,包括SVG导入功能和新的Gradle插件,可在构建时为API 20及更早版本生成VectorGrawable图标的PNG版本。还有一个用于将SVG转换为VectorDrawables的第三方工具。请记住,尽管可以使用XML定义矢量drawable,但文件格式不是SVG,并且并非所有SVG文件都可以成功转换。像图标这样的简单图形应该可以。

If you still need to generate PNGs yourself, you'll need to generate your icons at various resolutions. For ease of generating those PNGs I design icons as SVG and then export to the various sizes using Inkscape which is free and cross-platform. It's got some nice features for designing icons, including the Icon Preview view (see below), and it generates nice crisp PNGs.

如果您仍然需要自己生成PNG,则需要以各种分辨率生成图标。为了便于生成这些PNG,我将图标设计为SVG,然后使用免费和跨平台的Inkscape导出为各种大小。它有一些很好的设计图标功能,包括图标预览视图(见下文),它可以生成漂亮的清晰PNG。

在Android上使用SVG图标的最佳做法是什么?

#3


31  

This is what we are using to transform a SVG file into multiple resolutions. For example, to generate the launch icon: svg2png -w48 icon.svg

这就是我们用来将SVG文件转换为多种分辨率的方法。例如,要生成启动图标:svg2png -w48 icon.svg

#!/bin/bash -e
# Transforms a SVG into a PNG for each platform
# Sizes extracted from
# http://developer.android.com/design/style/iconography.html

[ -z $2 ] && echo -e "ERROR: filename and one dimension (-w or -h) is required, for example:\nsvg2png -w48 icon.svg\n" && exit 1;
FILENAME=$2
DEST_FILENAME=`echo $2 | sed s/\.svg/\.png/`
FLAG=`echo $1 | cut -c1-2`
ORIGINAL_VALUE=`echo $1 | cut -c3-`

if [ "$FLAG" != "-w" ] && [ "$FLAG" != "-h" ]; then
    echo "Unknown parameter: $FLAG" 
    exit 1
fi

# PARAMETERS: {multiplier} {destination folder}
function export {
  VALUE=$(echo "scale=0; $ORIGINAL_VALUE*$1" | bc -l)
  CMD="inkscape $FLAG$VALUE --export-background-opacity=0 --export-png=src/main/res/$2/$DEST_FILENAME src/main/svg/$FILENAME > /dev/null"
  echo $CMD
  eval $CMD
} 

export 1 drawable-mdpi
export 1.5 drawable-hdpi
export 2 drawable-xhdpi
export 3 drawable-xxhdpi
export 4 drawable-xxxhdpi

#4


14  

Good news everyone! Since android support library 23.2 we can use svg-s till back to API level 7!

大家好消息!由于android支持库23.2我们可以使用svg-s直到回到API级别7!

If you wanna be compatible backwards only till Lollipop (API 21) check Mark Whitaker's answer, but if you want to go below you need to add these lines to your build.gradle:

如果你想向后兼容直到Lollipop(API 21)检查Mark Whitaker的答案,但如果你想要进入下面,你需要将这些行添加到你的build.gradle:

// Gradle Plugin 2.0+ (if you using older version check the library announcement link)
android {  
    defaultConfig {  
        vectorDrawables.useSupportLibrary = true  
    }  
}  

Also keep in mind that:

还要记住:

  • instead of android:src you need to use the app:srcCompat attribute in ImageViews.
  • 而不是android:src你需要在ImageViews中使用app:srcCompat属性。
  • you cannot use svg-s in StateListDrawables or other xml drawables, create them programmatically instead.
  • 你不能在StateListDrawables或其他xml drawables中使用svg-s,而是以编程方式创建它们。
  • you cannot use the android:background attribute or View.setBackgroundResource() function, use the View.setBackground() instead.
  • 你不能使用android:background属性或View.setBackgroundResource()函数,而是使用View.setBackground()。
  • you cannot use svg-s in case of Notifications.
  • 在通知的情况下,您不能使用svg-s。

#5


7  

Since nacho-coloma's answer helped me, I've taken his excellent script and made it slightly easier to use on a daily basis.

由于nacho-coloma的回答对我有所帮助,因此我采用了他出色的脚本,使其每天使用起来更容易一些。

First:

第一:

  1. Create directory drawable-svg next to your res directory.
  2. 在res目录旁边创建目录drawable-svg。
  3. Place your svg files and this script in drawable-svg.
  4. 将您的svg文件和此脚本放在drawable-svg中。
  5. Make the script executable.
  6. 使脚本可执行。
  7. Run it. In Ubuntu you can simply double-click it in Nautilus and make it run in a terminal.
  8. 运行。在Ubuntu中,您只需在Nautilus中双击它并使其在终端中运行即可。

And later when you get new svg files:

以后当你得到新的svg文件时:

  1. Place new svg files in drawable-svg and run the script again.
  2. 将新的svg文件放在drawable-svg中并再次运行该脚本。

By default it will do what you want: Scale every svg file into png files and put them into ../res/drawable-mdpi, ../res/drawable-hdpi etc.

默认情况下,它会执行您想要的操作:将每个svg文件扩展为png文件并将它们放入../res/drawable-mdpi,../res/drawable-hdpi等。

The script takes two parameters:

该脚本有两个参数:

  1. The svg file pattern to scale, default: *.svg
  2. 要扩展的svg文件模式,默认值:* .svg
  3. The base directory for put, default ../res/ (i.e. your res directory with the above mentioned setup).
  4. put的基本目录,默认为../res/(即具有上述设置的res目录)。

You can experiment by scaling a single svg into pngs in the current directory like this:

您可以通过将单个svg缩放到当前目录中的png来进行试验,如下所示:

$ ./svg2png test.svg .

Or simply process all images:

或者只是处理所有图像:

$ ./svg2png

I guess you could place the drawable-svg inside the res directory, but I haven't looked into what gets wrapped up in the final APK. Also, my svg files have - in their names, which Android doesn't like, and my script takes care of renaming the png files to something valid on Android.

我想你可以将drawable-svg放在res目录中,但我没有查看最终APK中包含的内容。此外,我的svg文件 - 在他们的名字中,Android不喜欢,并且我的脚本负责将png文件重命名为在Android上有效的东西。

I'm using ImageMagick for the conversion which is slightly more standard that Inkscape (though I liked the approach). Both methods are included in the script for reference.

我正在使用ImageMagick进行转换,这比Inkscape稍微标准一点(虽然我喜欢这种方法)。这两种方法都包含在脚本中以供参考。

Here's the script:

这是脚本:

#!/bin/bash

scalesvg ()
{
    svgfile="$1"
    pngdir="$2"
    pngscale="$3"
    qualifier="$4"

    svgwidthxheight=$(identify "$svgfile" | cut -d ' ' -f 3)
    svgwidth=${svgwidthxheight%x*}
    svgheight=${svgwidthxheight#*x}

    pngfile="$(basename $svgfile)" # Strip path.
    pngfile="${pngfile/.svg/.png}" # Replace extension.
    pngfile="${pngfile/[^A-Za-z0-9._]/_}" # Replace invalid characters.
    pngfile="$pngdir/$qualifier/$pngfile" # Prepend output path.

    if [ ! -d $(dirname "$pngfile") ]; then
        echo "WARNING: Output directory does not exist: $(dirname "$pngfile")"
        #echo "Exiting"
        #exit 1
        echo "Outputting here instead: $pngfile"
        pngfile="$qualifier-${svgfile/.svg/.png}"
    fi

    pngwidth=$(echo "scale=0; $svgwidth*$pngscale" | bc -l)
    pngheight=$(echo "scale=0; $svgheight*$pngscale" | bc -l)
    pngdensity=$(echo "scale=0; 72*$pngscale" | bc -l) # 72 is default, 

    echo "$svgfile ${svgwidth}×${svgheight}px -> $pngfile ${pngwidth}×${pngheight}px @ $pngdensity dpi"

    convert -background transparent -density $pngdensity "$svgfile" "$pngfile"
    #inkscape -w${pngwidth} --export-background-opacity=0 --export-png="$pngfile" "$svgfile" > /dev/null
    #convert "$svgfile" -background transparent -scale ${pngwidth}x${pngheight} "$pngfile"
}



svgfiles="$1"
svgfiles="${svgfiles:=*.svg}" # Default to input all *.svg in current dir.

pngdir="$2"
pngdir="${pngdir:=../res}" # Default to place output pngs to ../res, ie. ../res/drawable-hdpi etc.

for svgfile in $svgfiles; do
    echo "Scaling $svgfile ..."
    scalesvg "$svgfile" "$pngdir" 0.75 drawable-ldpi
    scalesvg "$svgfile" "$pngdir" 1    drawable-mdpi
    scalesvg "$svgfile" "$pngdir" 1.5  drawable-hdpi
    scalesvg "$svgfile" "$pngdir" 2    drawable-xhdpi
    scalesvg "$svgfile" "$pngdir" 3    drawable-xxhdpi
    scalesvg "$svgfile" "$pngdir" 4    drawable-xxxhdpi
done

echo -n "Done."
read # I've made it wait for Enter -- convenient when run from Nautilus.

#6


6  

Another option is to convert your SVG assets into TTF font type. Include the font on your app and use it that way. This does the trick for monochromatic simple shapes.

另一种选择是将SVG资产转换为TTF字体类型。在您的应用中包含该字体并以此方式使用它。这就是单色简单形状的技巧。

There are several free conversion tools.

有几种免费的转换工具。

#7


5  

Android Support Library 23.2 Support Vector Drawables and Animated Vector Drawables

Android支持库23.2支持矢量Drawables和动画矢量Drawables

  1. add vectorDrawables.useSupportLibrary = true to your build.gradle file.
  2. 将vectorDrawables.useSupportLibrary = true添加到build.gradle文件中。
  3. Use app:srcCompat="@drawable/ic_add" instead of android:src="..." or setImageResource() for your ImageView
  4. 使用app:srcCompat =“@ drawable / ic_add”而不是android:src =“...”或setImageResource()为您的ImageView

http://android-developers.blogspot.sk/2016/02/android-support-library-232.html

http://android-developers.blogspot.sk/2016/02/android-support-library-232.html

#8


3  

SVG icons are not a good option to use directly on a device if they need to be scaled to many different sizes, which is usually why you'd want to use vector format in the first place. A large icon will never scale down gracefully because, well, computer displays are made out of pixels. So the lines of the vector image may get aligned "in between pixels", creating a blurry border. Moreover, large icons need more details than small icons, which need very few details. A detailed icon does not look good in very small size, and a simple icon does not look good when scaled into very large size. I recently read an excellent article on this by a professional UI designer: About those vector icons.

SVG图标不是直接在设备上使用的好选项,如果它们需要缩放到许多不同的大小,这通常是你想要首先使用矢量格式的原因。大图标永远不会正常缩小,因为计算机显示器是由像素组成的。因此,矢量图像的线条可以“在像素之间”对齐,从而产生模糊的边界。此外,大图标需要比小图标更多的细节,小图标需要很少的细节。在非常小的尺寸中,详细的图标看起来不太好,当缩放到非常大的尺寸时,简单的图标看起来不太好。我最近阅读了一篇由专业UI设计师撰写的优秀文章:关于那些矢量图标。

#9


2  

I've just posted a script for generating all the platform icons for PhoneGap apps that may be of value. Yet to add code for generating screens.

我刚刚发布了一个脚本,用于生成可能有价值的PhoneGap应用程序的所有平台图标。然而,要添加用于生成屏幕的代码。

#10


2  

I've just started using Victor, an open source library by Trello, to convert SVG files to PNG files of the various required resolutions during build time.

我刚刚开始使用Trello的开源库Victor,在构建期间将SVG文件转换为各种所需分辨率的PNG文件。

PROS

PROS

  • You won't have to run a script or tool to create various PNG files every time you change or add an icon. (You do need to hit Rebuild in Android Studio when you've added a new svg file or renamed an existing one)
  • 每次更改或添加图标时,您都不必运行脚本或工具来创建各种PNG文件。 (当您添加新的svg文件或重命名现有文件时,您需要在Android Studio中点击Rebuild)
  • No PNG's in your source, so there's less clutter.
  • 您的来源中没有PNG,因此杂乱程度较低。

CONS

缺点

  • The only downside I've seen so far is that Android Studio doesn't yet recognize generated resources in XML, so you'll get some red warnings in your XML files and you don't have autocomplete for your SVG based drawables. It builds fine though, and this issue should be fixed in a future version of Android Studio.
  • 到目前为止我唯一看到的缺点是Android Studio尚未识别XML中生成的资源,因此您会在XML文件中收到一些红色警告,并且您没有基于SVG的drawable的自动完成功能。它构建得很好,这个问题应该在Android Studio的未来版本中修复。

If you use SVG generated by http://materialdesignicons.com/ be sure to either download the whole file, or copy from the 'SVG File'-tab when choosing 'View SVG'

如果您使用http://materialdesignicons.com/生成的SVG,请务必下载整个文件,或者在选择“查看SVG”时从“SVG文件”选项卡复制

#11


0  

I've never had much luck running Linux shell scripts in Cygwin on Windows. So here is a batch file that does what Nacho Coloma's bash script does. One small difference, is that this batch file requires both an input and an output file name, as in "svg2png -w24 input.svg output.png".

我在Windows上运行Cygwin中的Linux shell脚本时从来没有太多运气。所以这是一个批处理文件,它可以完成Nacho Coloma的bash脚本所做的工作。一个小的区别是,这个批处理文件需要输入和输出文件名,如“svg2png -w24 input.svg output.png”。

Set up an "svg" folder in your project's src/main directory and copy your SVG files and this batch file to that folder, per Stephan's instructions. Run the batch file from the svg folder. If you're on 32-bit Windows, then you will likely need to change the path to Inkscape to use "Program Files (x86)".

在项目的src / main目录中设置“svg”文件夹,并根据Stephan的说明将SVG文件和此批处理文件复制到该文件夹​​。从svg文件夹运行批处理文件。如果您使用的是32位Windows,则可能需要更改Inkscape的路径以使用“Program Files(x86)”。

@echo off
echo Convert an SVG file to a PNG resource file with multiple resolutions.

rem Check the arguments
set temp=%1
set switch=%temp:~0,2%
set pixels=%temp:~2%
if not "%switch%"=="-w" (
if not "%switch%"=="-h" (
echo Error:  Invalid image width or height switch.  Use -w or -h, with target image size in dp appended.
goto :error
))
echo %pixels%| findstr /r /c:"^[1-9][0-9]*$" >nul
if errorlevel 1 (
echo Error:  Invalid numeric image size.  Image size must be a positive integer.
goto :error
)
if "%3"=="" (
echo Error:  Not enough arguments.
goto :error
)
if not "%4"=="" (
echo Error:  Too many arguments.
goto :error
)

call :export %1 %2 %3 mdpi
call :export %1 %2 %3 hdpi
call :export %1 %2 %3 xhdpi
call :export %1 %2 %3 xxhdpi
call :export %1 %2 %3 xxxhdpi
exit /b

:export
rem parameters: <width/height> <input-file> <output-file> <density>

set temp=%1
set switch=%temp:~0,2%
set pixels=%temp:~2%

if %4==mdpi set /a size=%pixels%
if %4==hdpi set /a size=%pixels%*3/2
if %4==xhdpi set /a size=%pixels%*2
if %4==xxhdpi set /a size=%pixels%*3
if %4==xxxhdpi set /a size=%pixels%*4

echo %size% pixels ../res/drawable-%4/%3
"C:\Program Files\Inkscape\inkscape.exe" %switch%%size% --export-background-opacity=0 --export-png=../res/drawable-%4/%3 %2
exit /b

:error
echo Synopsis: svg2png -w^<width-pixels^>^|-h^<height-pixels^> ^<input-file^> ^<output-file^>
echo Example:  svg2png -w24 "wifi white.svg" wifi_connect_24dp.png
exit /b

#12


0  

svg is awesome. who want use svg:

svg太棒了。谁想要使用svg:

right click on drawable "new/Vector Asset" choose "material icon" for default icons and "locale SVG file" for your file in your computer hard drive and in "resource name" type name for svg file then click on "next" button and "finish"

右键单击drawable“new / Vector Asset”为您的计算机硬盘驱动器中的文件选择“material icon”作为默认图标和“locale SVG file”,在svg文件的“resource name”类型名称中单击“next”按钮和“完成”

and you can use that in drawable. fillcolor must be hard code.

你可以在drawable中使用它。 fillcolor必须是硬代码。

simple example

简单的例子

navigation_toggle.xml

navigation_toggle.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FFFFFF"
        android:pathData="M3,18h18v-2H3v2zm0,-5h18v-2H3v2zm0,-7v2h18V6H3z"/>
</vector>