一、
相关概念
1.
Drawable
就是一个可画的
对象,其可能是一张位图(
BitmapDrawable
),也可能是一个
图形(
ShapeDrawable
),还有可能是一
个图层(
LayerDrawable
),我们根据画图的需求,创建相应的可画对象
2.
Canvas
画布,绘制的目
的区域,用于绘图
3.
Bitmap
位图,用于图的
处理
4.
Matrix
矩阵,此例中用
于操作图片
二、
步骤
1.
把
drawable
画到位图对象上
2.
对位图对象做缩放(或旋转等)操作
3.
把位图再转换成
drawable
三、
示例
static Bitmap
drawableToBitmap(Drawable drawable)
// drawable
转换成
bitmap
{
int width =
drawable.getIntrinsicWidth();
//
取
drawable
的长宽
int
height = drawable.getIntrinsicHeight();
Bitmap.Config config = drawable.getOpacity() !=
PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888:Bitmap.Config.RGB_565;
//
取
drawable
的颜色格式
Bitmap
bitmap = Bitmap.createBitmap(width, height, config);
//
建立对应
bitmap
Canvas canvas = new Canvas(bitmap);
//
建立对应
bitmap
的画布
drawable.setBounds(0,
0, width, height);
drawable.draw(canvas);
//
把
drawable
内容画到画布中
return
bitmap;
}
static Drawable zoomDrawable(Drawable drawable, int w, int h)
{
int
width = drawable.getIntrinsicWidth();
int height= drawable.getIntrinsicHeight();
Bitmap oldbmp = drawableToBitmap(drawable);
// drawable
转换成
bitmap
Matrix matrix = new Matrix();
//
创建操作图片用的
Matrix
对象
float
scaleWidth = ((float)w / width);
//
计算缩放比例
float scaleHeight = ((float)h /
height);
matrix.postScale(scaleWidth,
scaleHeight);
//
设置缩放比例
Bitmap newbmp =
Bitmap.createBitmap(oldbmp, 0, 0, width, height, matrix, true);
//
建立新的
bitmap
,其内容是对原
bitmap
的缩放后的图
return
new BitmapDrawable(newbmp);
//
把
bitmap
转换成
drawable
并返回
}
}