一、View 转 Bitmap的几种情况
1、ScrollView 转成Bitmap
public void convertViewToBitmap(ScrollView scrollView) {
int h = 0;
for (int i = 0; i < scrollView.getChildCount(); i++) {
h += scrollView.getChildAt(i).getHeight();
}
// 创建对应大小的bitmap
posterBitmap = Bitmap.createBitmap(scrollView.getWidth(), h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(posterBitmap);
scrollView.draw(canvas);
}
2、RelativeLayout 转成Bitmap
这个View如果没有再布局,则需要设置宽高才能转
private Bitmap createBitmap(RelativeLayout view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
c.drawColor(Color.WHITE);
view.draw(c);
return bitmap;
}
3、Canvas转成Bitmap
public Bitmap getBitmap() {
int w = UiUtil.dip2px(64), h = UiUtil.dip2px(72);
String mstrTitle = "感受Android带给我们的新体验";
final Bitmap mbmpTest = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mbmpTest);
canvas.drawColor(Color.BLACK);
Paint p = new Paint();
String familyName = "宋体";
Typeface font = Typeface.create(familyName, Typeface.BOLD);
p.setColor(Color.RED);
p.setTypeface(font);
p.setTextSize(22);
canvas.drawText(mstrTitle, 0, 100, p);
Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.mipmap.public_back);
Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(), R.mipmap.public_audio_introduce3);
Bitmap bitmap3 = BitmapFactory.decodeResource(getResources(), R.mipmap.public_praise_s);
canvas.drawBitmap(bitmap1, 0, 0, p);
canvas.drawBitmap(bitmap2, 30, 30, p);
canvas.drawBitmap(bitmap3, 60, 60, p);
bitmap1.recycle();
bitmap2.recycle();
bitmap3.recycle();
bitmap1=null;
bitmap2=null;
bitmap3=null;
return mbmpTest;
}
二、保存图片到相册
/**
* 屏幕截图保存
*/
public static void saveScreenShot(View view,BaseActivity activity) {
Bitmap bitmap = BitmapUtil.loadBitmapFromView(view);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
String filename;//声明文件名
//以保存时间为文件名
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
filename = sdf.format(date);
File file = new File(extStorageDirectory, filename + ".JPEG");//创建文件,第一个参数为路径,第二个参数为文件名
try {
outStream = new FileOutputStream(file);//创建输入流
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.close();
//这三行可以实现相册更新
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
activity.sendBroadcast(intent);//这个广播的目的就是更新图库,发了这个广播进入相册就可以找到你保存的图片了
activity.runOnUiThread(() -> Toast.makeText(activity, "保存成功", Toast.LENGTH_SHORT).show());
} catch (Exception e) {
activity.runOnUiThread(() -> Toast.makeText(activity, "保存失败", Toast.LENGTH_SHORT).show());
}
}