Android svg的适配问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zh_qianwei/article/details/77893273

在Android 使用SVG的适配主要集中在5.0以后和5.0以前系统

官网说明Android 5.0(API 级别 21)及更高版本会提供矢量图支持。如果应用的最低 API 级别低于以上版本,Vector Asset Studio 会将矢量图文件添加到项目中;另外,在构建时,Gradle 会创建不同分辨率的 PNG 光栅图像。Gradle 会生成 build.gradle 文件中的域特定语言 (DSL) generatedDensities 属性所指定的 PNG 密度。(注:矢量图就是svg的代码文件,光栅图就是自动生成的png)。

以上的官网的说明,下面我们来看下具体使用。
在5.0以前什么都不用做,5.0以前系统有二种方案可以使用。

第一种,生成png图
配置gradle,让svg生成对应版本的png图。如果不配系统会自动生成多套

  defaultConfig {
    vectorDrawables.generatedDensities = ['hdpi','xxhdpi']//低版本的build 命令是generatedDensities
}

在xml使用svg时可以直接android:src=“@drawable/icon_svg”
这种方案最大弊端就会造成apk体积增大

第二种使用support
使用 Support Library 23.2+ 兼容包,包含VectorDrawableCompat和AnimatedVectorDrawableCompat兼容类,Drawable最低SDK为Android 2.1,动画最低SDK为Android 3.0

dependencies {
  compile 'com.android.support:appcompat-v7:23.2.0'//具体版本自己需要改
}    

这里因为使用了support所以不需要在生成图片了

  defaultConfig {
    vectorDrawables.generatedDensities = []//低版本的build 命令是generatedDensities
    vectorDrawables.useSupportLibrary = true
}

在xml使用svg时不可以可以直接android:src;需使用app:srcCompat=“@drawable/icon_svg”
同时为了区分support包还是系统原声,我们需要在调用的时候修改相应代码

Activity需要继承AppCompatActivity
并且要加设置

   static {
       AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

xml
在 ImageView 等引用 VectorDrawable 资源时,需要使用app:srcCompat取代android:src
在非src属性的地方使用矢量图时,需要将矢量图用drawable容器(如StateListDrawable, InsetDrawable, LayerDrawable, LevelListDrawable, 和RotateDrawable)包裹起来使用。否则会在低版本的情况下报错。

代码使用
Resources resources = context.getResources(Resources, int, Theme);
Theme theme = context.getTheme();
Drawable drawable = VectorDrawableCompat.create(resources, R.drawable.vector_drawable, theme);
view.setBackground(drawable);
代码中需要进行Drawable的实现类型转换时,可使用以下代码段执行:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
VectorDrawable vectorDrawable = (VectorDrawable) drawable;
} else {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
}

参考https://developer.android.com/studio/write/vector-asset-studio.html
http://www.jb51.net/article/84610.htm
http://www.cnblogs.com/chenliyang/p/6542896.html

猜你喜欢

转载自blog.csdn.net/zh_qianwei/article/details/77893273