最近在使用 vector 图片时,发现从设计提供的 svg 导入后,老是会有黄色的提醒,看着怪难受的,具体如下:
提醒1:非常长的矢量路径(2710 个字符),这对性能不利。考虑降低精度、删除次要细节或栅格化矢量。
提醒2:资源引用在为 API < 24 的此矢量图标生成的图像中将无法正常工作;检查生成的图标以确保它看起来可以接受
具体来看下这两个提醒:
提醒1:
主要是对 path data 的路径字符长度有要求,测试了一下是超过 800 个字符就会有提醒,而且这长度过长,也的确会影响到渲染的效率。
对策:
-
让设计同学,重新切图,减少 path data ;
-
通过 svg 优化工具先对 svg 优化,然后再导入到项目中;
svgomg 是个好用又方便的 svg 在线优化工具,可调整各种参数对其进行优化,然后下载下来即可。如下图所示:
- 通过 VD 优化工具 avocado 命令进行优化
相对于 svgomg 来说,优势在于直接对 vector 的 xml 文件处理,处理完直接用就行,不需要再导入,此外由于它是个命令行工具,可以直接对 vd 文件进行批量处理,甚至可以自定义一个 task 任务去自动执行。
下载命令:
npm install -g avocado
使用方式:
Usage: avocado [options] [file]
Options:
-V, --version output the version number
-s, --string <string> input VD or AVD string
-i, --input <file> input file/directory, or "-" for STDIN
-o, --output <file> output file/directory (same as the input file by default), or "-" for STDOUT
-d, --dir <dir> optimizes and rewrite all *.xml files in a directory
-q, --quiet only output error messages
-h, --help output usage information
示例:
# Optimize (and overwrite) a VD/AVD file.
avocado vector.xml
# Optimize (and overwrite) multiple VD/AVD files.
avocado *.xml
# Optimize a VD/AVD file and write the output to a new file.
avocado vector.xml -o vector_min.xml
# Optimize a VD/AVD using standard input and standard output.
cat vector.xml | avocado -i - -o - > vector_min.xml
# Optimize (and overwrite) all of the VD/AVD files in a directory.
avocado -d path/to/directory
# Optimize all VD/AVD files in a directory and write them to a new directory.
avocado -d path/to/input/directory -o path/to/output/directory
# Optimize all files ending with '.xml' and write them to a new directory.
avocado *.xml -o path/to/output/directory
# Pass a string as input and write the output to a new file.
avocado -s '<vector>...</vector>' -o vector_min.xml
对于 2,3 种方式来说,工具只是尽可能去优化,可能优化过后,pathData 长度依然没有少于 800 字符,但对比之前是有一定的减少,所以最好的解决方式是让设计同学去处理。
提醒2:
这是个适配的问题,解决方法如下:
//For Gradle Plugin 2.0+
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
具体的关于 VectorDrawable 的介绍,可参考如下官方文档