美文网首页工作生活
SVG的兼容性处理

SVG的兼容性处理

作者: saygoodbye_e92e | 来源:发表于2019-07-01 16:35 被阅读0次

    SVG的适配

         由于SVG是在Android 5.0之后,提供支持的,所以在5.0之前的手机,需要做一些适配,目前有2中适配方式

    第一种,生成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'//具体版本自己需要改

    }   

    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;

    }

    相关文章

      网友评论

        本文标题:SVG的兼容性处理

        本文链接:https://www.haomeiwen.com/subject/xkqncctx.html