我用谷歌搜索,但找不到任何文章来描述 Android 中 Bitmap 和 Drawable 之间的区别。
4 回答
A Bitmap is a representation of a bitmap image (something like java.awt.Image). A Drawable is an abstraction of "something that can be drawn". It could be a Bitmap (wrapped up as a BitmapDrawable
), but it could also be a solid color, a collection of other Drawable objects, or any number of other structures.
Most of the Android UI framework likes to work with Drawable objects, not Bitmap objects. A View can accept any Drawable as a background. An ImageView can display a foreground Drawable. Images stored as resources are loaded as Drawable objects.
Drawable is something which can be drawn. E.g. layout, vector image (line, circle), font, image and so on
Bitmap - is specific type of Drawable which is image, like: PNG, JPEG or so
位图不是图像。Bitmap 是位图(注名:Bit-map)。这张地图代表了你可以在上面画东西的像素。它可能是您自己的自定义位图(不是图像),例如正方形:
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
或者您可以从图像创建位图对象:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.your_image);
位图是一个像素持有者。Canvas 用于在位图上(在位图像素上)绘制一些东西。
关于 Drawable 的一切都在上面进行了很好的描述。
TL;博士
有些人写道,你在 Canvas 上画画。你不会在 Canvas 上画画。您使用 Canvas 辅助方法绘制位图像素。
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.RED) // now all bitmap pixels became red
可绘制资源
Drawable
资源是可以绘制到屏幕上的图形的一般概念,您可以使用诸如 和 等属性的 API 检索或应用getDrawable(int)
到另一个 XML 资源。有几种不同类型的可绘制对象:android:drawable
android:icon
位图文件,位图图形文件(.png、.jpg 或 .gif)创建一个
BitmapDrawable
.九补丁文件,
PNG
具有可拉伸区域以允许根据内容 (.9.png) 调整图像大小的文件,创建一个NinePatchDrawable
.Layer List , A管理其他s
Drawable
的数组。Drawable
这些是按数组顺序绘制的,因此索引最大的元素被绘制在顶部,创建一个LayerDrawable
.状态列表,一个
XML
文件,它为不同的状态引用不同的位图图形(例如,当按下按钮时使用不同的图像),创建一个StateListDrawable
.Level List,一个
XML
文件,它定义了一个Drawable
管理多个备用Drawable
s 的文件,每个 s 都分配了一个最大数值,创建一个LevelListDrawable
.Transition Drawable,一个
XML
定义Drawable
可以在两个资源之间交叉淡入淡出的文件Drawable
,创建一个TransitionDrawable
.Inset Drawable,一个
XML
文件,它定义了一个以指定距离Drawable
插入另一个的文件。当需要一个小于视图实际边界的背景时,Drawable
这很有用。View
Drawble
Clip Drawable,一个
XML
文件定义了一个基于 this的当前级别值Drawable
剪辑另一个的文件,创建一个.Drawable
Drawable
ClipDrawable
Scale Drawable,一个
XML
文件定义了一个根据其当前级别值Drawable
更改另一个大小的文件,创建一个.Drawable
ScaleDrawable
Shape Drawable,一个
XML
定义几何形状的文件,包括颜色和渐变,创建一个ShapeDrawable
.
另请参阅动画资源文档以了解如何创建AnimationDrawable
.
注意:颜色资源也可以用作Ddrawable
in XML
。例如,在创建 时,您可以为属性 ( )StateListDrawable
引用颜色资源。android:drawable
android:drawable="@color/green"
位图
位图图像。Android 支持三种格式的位图文件:.png(首选)、.jpg(可接受)、.gif(不鼓励)。
您可以直接引用位图文件,使用文件名作为资源 ID,或者在 XML 中创建别名资源 ID。
注意:在构建过程中,aapt 工具可能会使用无损图像压缩自动优化位图文件。例如,不需要超过 256 种颜色的真彩色 PNG 可以转换为带有调色板的 8 位 PNG。这将产生相同质量的图像,但需要更少的内存。因此请注意,放置在此目录中的映像二进制文件可能会在构建期间发生更改。如果您打算将图像作为位流读取以便将其转换为位图,请将图像放在res/raw/
文件夹中,而不是对其进行优化。