当前位置:网站首页>你居然不懂Bitmap和Drawable? 相关知识大扫盲
你居然不懂Bitmap和Drawable? 相关知识大扫盲
2022-08-01 21:28:00 【代码与思维】
Bitmap是什么
Bitmap的基本思想就是用一个bit位来标记某个元素对应的Value,而Key即是该元素。由于采用了Bit为单位来存储数据,因此在存储空间方面,可以大大节省。
Bitmap 是位图信息的存储,即⼀个矩形图像每个像素的颜⾊信息的存储器。
Android从基础底层到架构成长的全套笔记,有需要完整版的朋友,可点击这里查看获取方式或者留言【Android】领取!
Drawable是什么
Drawable是一种可以在Canvas上进行绘制的抽象的概念,颜色、图片等都可以是一个Drawable。Drawable可以通过XML定义,或者通过代码创建。Android中Drawable是一个抽象类,每个具体的Drawable都是其子类。简单来讲,其可以理解为:图像。
Drawable 内部存储的是绘制规则,这个规则可以是⼀个具体的 Bitmap,也可以是⼀个纯粹的颜⾊,甚⾄可以是⼀个抽象的、灵活的描述。Drawable 可以不含有具体的像素信息,只要它含有的信息⾜以在 draw(Canvas) ⽅法被调⽤时进⾏绘制就够了。由于 Drawable 存储的只是绘制规则,因此在它的 draw() ⽅法被调⽤前,需要先调⽤ Drawable.setBounds() 来为它设置绘制边界。
Drawable的优点:
- 使用简单,比自定义View成本低
- 非图片类的drawable所占空间小,能减小apk大小
Bitmap和Drawable的相互转换
//drawable convert bitmap
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if (bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if ((drawable.getIntrinsicWidth() <= 0) || (drawable.getIntrinsicHeight() <= 0)) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
}
else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
//bitmap convert drawable
public static Drawable bitmapToDrawable(Context context, Bitmap bitmap) {
return new BitmapDrawable(context.getResources(), bitmap);
}
事实上,由于 Bitmap 和 Drawable 是两个不同的概念,因此确切地说它们并不是互相「转换」,⽽是从其中⼀个获得另⼀个的对象:
- Bitmap -> Drawable:创建⼀个 BitmapDrawable。
- Drawable -> Bitmap:如果是 BitmapDrawable,使⽤BitmapDrawable.getBitmap() 直接获取;如果不是,创建⼀个 Bitmap和⼀个 Canvas,使⽤ Drawable 通过 Canvas 把内容绘制到 Bitmap 中。
作者:Arrom
转载平台:掘金
链接:https://juejin.cn/post/7126798240573292558
边栏推荐
猜你喜欢
随机推荐
图片识别商品接口 API:天猫淘宝
C Pitfalls and pitfalls Appendix B Interview with Koenig and Moo
基于php影视资讯网站管理系统获取(php毕业设计)
2022牛客多校联赛第五场 题解
An online JVM FullGC made it impossible to sleep all night and completely crashed~
365天挑战LeetCode1000题——Day 046 生成每种字符都是奇数个的字符串 + 两数相加 + 有效的括号
Port protocol for WEB penetration
牛血清白蛋白刺槐豆胶壳聚糖缓释纳米微球/多西紫杉醇的纳米微球DTX-DHA-BSA-NPs
Jmeter combat | Repeated and concurrently grabbing red envelopes with the same user
C pitfalls and pitfalls Chapter 8 Suggestions and answers 8.2 Answers
LeetCode·每日一题·1374.生成每种字符都是奇数个的字符串·模拟
Spark集群搭建
C Pitfalls and Defects Chapter 7 Portability Defects 7.8 Size of Random Numbers
基于php酒店在线预定管理系统获取(php毕业设计)
51.【结构体初始化的两种方法】
0DFS中等 LeetCode6134. 找到离给定两个节点最近的节点
C pitfalls and pitfalls Chapter 7. Portability pitfalls 7.10 Free first, then realloc
Record the first PR to an open source project
LVS负载均衡群集
How to make the timer not execute when the page is minimized?