android中代码解析drawable的xml文件

来源:互联网 发布:mysql like语句 编辑:程序博客网 时间:2024/06/05 20:53

本次主要分析我们在项目中解析自定义drawabale.xml文件是怎么转化为Drawable对象
映射关系如下:

  • drawable path =》VectorDrawable
  • drawable color =》 ColorDrawable
  • drawable sharp =》 ShapeDrawable

这些是最基本的映射关系,当然还有其他映射Drawable,比如:
BitmapDrawable,CircularBorderDrawable,ClipDrawable,AnimationDrawable,RotateDrawable等等
这里分享一个小案例就是我们定义一个drawabale.xml文件,怎么最后显示到我们的界面上去,上代码一步一步分析:
获取Drawable对象:

ContextCompat.getDrawable(getContext(), resId)

Drawable对象转换BitmapDrawable关键代码:(d =》drawable对象)

int width = d.getIntrinsicWidth();            int height = d.getIntrinsicHeight();            width = width > 0 ? width : mCursorWidth;            height = height > 0 ? height : mCursorHeight;            // 取 drawable 的颜色格式            Bitmap.Config config = d.getOpacity() != PixelFormat.OPAQUE ?                    Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;            // 建立对应 bitmap            Bitmap bitmap = Bitmap.createBitmap(width, height, config);            // 建立对应 bitmap 的画布            Canvas canvas = new Canvas(bitmap);            //把 drawable 内容画到画布中            d.setBounds(0, 0, width, height);            d.draw(canvas);            if (mCursorWidth > 0 && mCursorHeight > 0) {                Matrix matrix = new Matrix();                matrix.postScale(width, mCursorWidth, height, mCursorHeight);                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);                mCursorBitmapDrawable = new BitmapDrawable(getResources(), bitmap);            } else {                mCursorBitmapDrawable = new BitmapDrawable(getResources(), bitmap);            }

最后就是将BitmapDrawable对象draw到View,就可以显示出来了