已测量过的View生成Bitmap
即经过测量、布局、绘制并显示在界面上的View,此类View无需再次进行测量和布局,可直接将内容绘制到指定的Bitmap上。
/**
* 绘制已经测量过的View
*/
private static Bitmap drawMeasureView(View view) {
int width = view.getWidth();
int height = view.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
未测量过的View生成Bitmap
直接Inflate后并未显示在界面的View,此类View必须手动进行测量和布局后,方可进行绘制,否则获取不到对应的宽高和内容。
/**
* 先测量和布局,再生成Bitmap
*/
public static Bitmap getBitmap(View view) {
// 测量
int widthSpec = View.MeasureSpec.makeMeasureSpec(screenWidth, View.MeasureSpec.AT_MOST);
int heightSpec = View.MeasureSpec.makeMeasureSpec(screenHeight, View.MeasureSpec.AT_MOST);
view.measure(widthSpec, heightSpec);
// 布局
int measuredWidth = view.getMeasuredWidth();
int measuredHeight = view.getMeasuredHeight();
view.layout(0, 0, measuredWidth, measuredHeight);
// 绘制
int width = view.getWidth();
int height = view.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
多张Bitmap合并为一张
将多张Bitmap按顺序从上到下合并为一张,如果图片的宽度不同,则进行等比缩放后再进行合并绘制。
/**
* 将用户输入的图片从上到下拼接到一起
* 如果图片宽度不一致,则进行等比缩放后再拼接
*/
public static Bitmap concat(Bitmap... bitmaps) {
// 获取图片的最大宽度
int maxWidth = bitmaps[0].getWidth();
for (Bitmap bitmap : bitmaps) {
maxWidth = Math.max(maxWidth, bitmap.getWidth());
}
// 对图片进行缩放并计算拼接后的图片高度
int totalHeight = 0;
for (int i = 0; i < bitmaps.length; i++) {
Bitmap bitmap = bitmaps[i];
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scale = maxWidth * 1f / width;
int scaleHeight = (int) (height * scale);
totalHeight = totalHeight + scaleHeight;
bitmaps[i] = Bitmap.createScaledBitmap(bitmap, maxWidth, scaleHeight, false);
}
// 从上到下依次拼接
Bitmap newBitmap = Bitmap.createBitmap(maxWidth, totalHeight, Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(newBitmap);
int offsetTop = 0;
for (Bitmap bitmap : bitmaps) {
int height = bitmap.getHeight();
canvas.drawBitmap(bitmap, 0, offsetTop, null);
offsetTop += height;
}
return newBitmap;
}
网友评论