private void printScreen(boolean save) {//截屏
View view = this.getWindow().getDecorView();//this是当前的Activity
// if (view.isDrawingCacheEnabled()) {
view.setDrawingCacheEnabled(true);
Calendar c = Calendar.getInstance();
String date = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.HOUR_OF_DAY) + "-" + c.get(Calendar.MINUTE) + "-" + c.get(Calendar.SECOND);
// }
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
imagePath = ConstValue.MY_ALBUM_DIR + "/" + date + ".jpg";//路径
writePhotoJpg(bmp, imagePath);
// FileSaveAsync myAsync = new FileSaveAsync(bmp, imagePath, true);
// myAsync.execute();
}
保存到sd卡下的方法:(记得加上写入sd卡的权限)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission>
public void writePhotoJpg(Bitmap data, String pathName) {
File file = new File(pathName);
try {
file.createNewFile();
// BufferedOutputStream os = new BufferedOutputStream(
// new FileOutputStream(file));
FileOutputStream os = new FileOutputStream(file);
data.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
MyDebug.i("writePhotoJpg");
} catch (Exception e) {
e.printStackTrace();
}
}
public void writePhotoPng(Bitmap data, String pathName) {
File file = new File(pathName);
try {
file.createNewFile();
FileOutputStream os = new FileOutputStream(file);
// BufferedOutputStream os = new BufferedOutputStream(
// new FileOutputStream(file));
data.compress(Bitmap.CompressFormat.PNG, 100, os);
os.flush();
os.close();
MyDebug.i("writePhotoPng");
} catch (Exception e) {
e.printStackTrace();
}
}
另外几种方法,没仔细测试过:仅供参考
//抓屏的方式生成照片
public static Bitmap printScreen(Context context) {
View view = ((Activity) context).getWindow().getDecorView();
// if (view.isDrawingCacheEnabled()) {
view.setDrawingCacheEnabled(true);
// Calendar c = Calendar.getInstance();
// String date = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.HOUR_OF_DAY) + "-" + c.get(Calendar.MINUTE) + "-" + c.get(Calendar.SECOND);
// }
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
return bmp;
/*imagePath = ConstValue.MY_ALBUM_DIR + "/" + date + ".jpg";
ImageFile.writePhotoJpg(bmp, imagePath);*/
// FileSaveAsync myAsync = new FileSaveAsync(bmp, imagePath, true);
// myAsync.execute();
}
public static Bitmap catchScreen(View v1) {
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
return bitmap;
}