我是靠谱客的博主 笨笨老虎,这篇文章主要介绍Andrid Bimap 和 DrawableBitmap 和 Drawable,现在分享给大家,希望可以做个参考。

BitmapDrawable

1、Bitmap 是什么?

Bitmap

Bitmap 存储的是每一个像素点的信息

Drawable 是一个可画的对象, 可能是一个位图(BitmapDrawable), 也可能是一个图形(ShapeDrawable)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
class DrawableView(context: Context?, attrs: AttributeSet?) : View(context, attrs) { var mDrawable = MeshDrawable() override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) canvas ?: return mDrawable.apply { setBounds(0, 0, width, height) draw(canvas) } } }

2、BitmapDrawable 互转(https://corochann.com/convert-between-bitmap-and-drawable-313.html)

Bitmap to Drawable
复制代码
1
2
Drawable d = new BitmapDrawable(getResources(), bitmap);
Drawable to Bitmap
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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) { // Single color bitmap will be created of 1x1 pixel 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; }

3、自定义 Drawable

自定义 Drawable 一般都是为了重用, 因为大多数时候系统提供的就够用了, 比如 ColorDrawable

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class MeshDrawable : Drawable() { /** * 画笔 */ private val mPaint by lazy { Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.parseColor("#1E88E5") strokeWidth = dp2px(3F) } } private val INTERVAL by lazy { dp2px(50F).toInt() } override fun draw(canvas: Canvas) { // 横着画竖线 for (x in 0 until bounds.right step INTERVAL) { canvas.drawLine(x.toFloat(), bounds.top.toFloat(), x.toFloat(), bounds.bottom.toFloat(), mPaint) } // 竖着画横线 for (y in 0 until bounds.bottom step INTERVAL) { canvas.drawLine(bounds.left.toFloat(), y.toFloat(), bounds.right.toFloat(), y.toFloat(), mPaint) } } override fun setAlpha(alpha: Int) { mPaint.alpha = alpha } override fun getAlpha(): Int = mPaint.alpha override fun setColorFilter(colorFilter: ColorFilter?) { mPaint.colorFilter = colorFilter } override fun getColorFilter(): ColorFilter? = mPaint.colorFilter override fun getOpacity(): Int { return when { mPaint.alpha == 0xff -> PixelFormat.OPAQUE mPaint.alpha == 0 -> PixelFormat.TRANSPARENT else -> PixelFormat.TRANSLUCENT } } }

最后

以上就是笨笨老虎最近收集整理的关于Andrid Bimap 和 DrawableBitmap 和 Drawable的全部内容,更多相关Andrid内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部