今天我们所说的是底层图形类android.graphics。
##1、概念
Bitmap:称作位图,一般位图的文件格式后缀为bmp,当然编码器也有很多如RGB565、RGB888、ARGB8888。作为一种像素的显示对象执行效率高,但是存储效率低的缺点也很明显。就理解为一种bmp格式图像存储对象。
Drawable:作为Android下通用的绘制图形对象,它可以装载常用格式的图像,比如GIF、PNG、JPG,当然也支持bmp,当然还提供一些高级的可视化对象,比如渐变、图形等。
Canvas:画布,我们可以看作是一种处理过程,使用各种方法来管理Bitmap、GL或者Path路径,同时它可以配合Matrix矩阵类给图像做旋转、缩放等操作,同时Canvas类还提供了裁剪、选取等操作。
Paint:可以把它看做一个画图工具,比如画笔、画刷。他管理了每个画图工具的字体、颜色、样式。 如果涉及一些Android游戏开发、显示特效可以通过这些底层图形类来高效实现自己的应用。
##2、代码实现
/**
*Bitmap的获取方式
*/
//1、raw-->Bitmap
//BitmapDrawable(Resources res, Bitmap bitmap)
//BitmapDrawable(Resources res, String filepath)
//BitmapDrawable(Resources res, InputStream is)
is = res.openRawResource(R.raw.raw_image);
bDraw = new BitmapDrawable(res, is);
bitmap = bDraw.getBitmap();
//2、id-->Bitmap
//getDrawable(int id, Resources.Theme theme) API22 以上
bDraw = (BitmapDrawable) res.getDrawable(R.drawable.ic_launcher);
bitmap = bDraw.getBitmap();
//3、id-->Bitmap
bitmap = BitmapFactory.decodeResource(res, R.drawable.ic_launcher);
//4、assets-->Bitmap
AssetManager am = getAssets();
is = am.open("assets_image.png");
bitmap = BitmapFactory.decodeStream(is);
//5、Bitmap-->BitmapDrawable
new BitmapDrawable(res, bitmap);
对ImageView实现Matrix矩阵操作
//1、直接对ImageView设置矩阵
Matrix matrix = new Matrix();
matrix.postRotate(15);
matrix.postSkew(0.2f, 0.3f);
mImageView.setImageMatrix(matrix);
android:scaleType="matrix"
//2、通过对Bitmap设置矩阵
private Bitmap scaleBitmap(Bitmap bitmap, int scaleWidth, int scaleHeight) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// 创建操作图片用的Matrix对象
Matrix matrix = new Matrix();
// 计算缩放比例
float sx = ((float) scaleWidth / w);
float sy = ((float) scaleHeight / h);
// 设置缩放比例
//matrix.postScale(sx, sy);
matrix.postRotate(15);
//matrix.postSkew(0.2f, 0.3f);
// 建立新的bitmap,其内容是对原bitmap的缩放后的图
Bitmap scaleBmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
return scaleBmp;
}
Matrix类的其他典型方法:
boolean postScale(float sx, float sy)//缩放
boolean postSkew(float kx, float ky)//扭曲
boolean postTranslate(float dx, float dy)//转换
boolean preConcat(Matrix other)//合并
boolean preRotate(float degrees)//旋转
byte字节和Bitmap进行转换:
//Bitmap-->byte
private byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream byteos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, byteos);
return byteos.toByteArray();
}
//byte-->Bitmap
private Bitmap Bytes2Bimap(byte[] image) {
if (image.length != 0) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
} else {
return null;
}
}