不多說廢話,直接上代碼
屏幕截圖任斋,親測可用猪叙,基于Activity
/**
* 屏幕截圖
* @param activity
* @return
*/
public static Bitmap screenShot(AppCompatActivity activity,String filePath) {
if (activity == null){
Logger.getLogger().e("screenShot--->activity is null");
return null;
}
View view = activity.getWindow().getDecorView();
//允許當(dāng)前窗口保存緩存信息
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
int navigationBarHeight = ScreenUtils.getNavigationBarHeight(view.getContext());
//獲取屏幕寬和高
int width = ScreenUtils.getScreenWidth(view.getContext());
int height = ScreenUtils.getScreenHeight(view.getContext());
// 全屏不用考慮狀態(tài)欄,有導(dǎo)航欄需要加上導(dǎo)航欄高度
Bitmap bitmap = null;
try {
bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, 0, width,
height + navigationBarHeight);
} catch (Exception e) {
// 這里主要是為了兼容異形屏做的處理,我這里的處理比較倉促穴翩,直接靠捕獲異常處理
// 其實vivo oppo等這些異形屏手機官網(wǎng)都有判斷方法
// 正確的做法應(yīng)該是判斷當(dāng)前手機是否是異形屏犬第,如果是就用下面的代碼創(chuàng)建bitmap
String msg = e.getMessage();
// 部分手機導(dǎo)航欄高度不占窗口高度,不用添加芒帕,比如OppoR15這種異形屏
if (msg.contains("<= bitmap.height()")){
try {
bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, 0, width,
height);
} catch (Exception e1) {
msg = e1.getMessage();
// 適配Vivo X21異形屏歉嗓,狀態(tài)欄和導(dǎo)航欄都沒有填充
if (msg.contains("<= bitmap.height()")) {
try {
bitmap = Bitmap.createBitmap(view.getDrawingCache(), 0, 0, width,
height - ScreenUtils.getStatusHeight(view.getContext()));
} catch (Exception e2) {
e2.printStackTrace();
}
}else {
e1.printStackTrace();
}
}
}else {
e.printStackTrace();
}
}
//銷毀緩存信息
view.destroyDrawingCache();
view.setDrawingCacheEnabled(false);
if (null != bitmap){
try {
compressAndGenImage(bitmap,filePath);
Logger.getLogger().d("--->截圖保存地址:" + filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
View截圖,親測可用???參考
/**
* view截圖
* @return
*/
public static void viewShot(@NonNull final View v, @Nullable final String filePath,
@Nullable final ShotCallback shotCallback){
if (null == v) {
Logger.getLogger().e("view is null");
return;
}
v.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
v.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
v.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
// 核心代碼start
Bitmap bitmap = Bitmap.createBitmap(v.getWidth() , v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
// end
String savePath = filePath;
if (TextUtils.isEmpty(savePath)){
savePath = createImagePath();
}
try {
compressAndGenImage(bitmap,savePath);
Logger.getLogger().d("--->截圖保存地址:" + savePath);
} catch (IOException e) {
e.printStackTrace();
}
if (null != shotCallback){
shotCallback.onShotComplete(bitmap,savePath);
}
}
});
}
關(guān)于View截圖背蟆,如果需要實現(xiàn)后臺截圖鉴分,也就是截圖的時候view不在屏幕上顯示,只需要把要截圖的View設(shè)置成invisible就可以了带膀。
另外再附上生成圖片和保存到手機SD卡上的方法志珍,一步到位,直接粘貼拿去就用
private static final String IMAGE_FILE_NAME_TEMPLATE = "Image%s.jpg";
private static final String IMAGE_FILE_PATH_TEMPLATE = "%s/%s";
/**
* 存儲到sdcard
*
* @param bmp
* @param maxSize 為0不壓縮
* @return
*/
public static String saveToSD(Bitmap bmp,int maxSize) {
if (bmp == null){
Logger.getLogger().e("saveToSD--->bmp is null");
return "";
}
//判斷sd卡是否存在
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//文件名
long systemTime = System.currentTimeMillis();
String imageDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(systemTime));
String mFileName = String.format(IMAGE_FILE_NAME_TEMPLATE, imageDate);
//文件全名
String mstrRootPath = FileUtil.getPackageDCIMPath(AFApplication.applicationContext);
String filePath = String.format(IMAGE_FILE_PATH_TEMPLATE, mstrRootPath, mFileName);
Logger.getLogger().d("saveToSD--->file path:" + filePath);
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Logger.getLogger().d("saveToSD--->file AbsolutePath:" + filePath);
try {
compressAndGenImage(bmp,filePath,maxSize);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
bmp.recycle();
}
return filePath;
}
return "";
}
public static String createImagePath(){
//判斷sd卡是否存在
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//文件名
long systemTime = System.currentTimeMillis();
String imageDate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(systemTime));
String mFileName = String.format(IMAGE_FILE_NAME_TEMPLATE, imageDate);
//文件全名
String mstrRootPath = FileUtil.getPackageDCIMPath(AFApplication.applicationContext);
String filePath = String.format(IMAGE_FILE_PATH_TEMPLATE, mstrRootPath, mFileName);
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return filePath;
}
return "";
}
public static void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
// scale
int options = 100;
// Store the bitmap into output stream(no compress)
image.compress(Bitmap.CompressFormat.JPEG, options, os);
// Compress by loop
if (maxSize != 0) {
while (os.toByteArray().length / 1024 > maxSize) {
// Clean up os
os.reset();
// interval 10
options -= 10;
image.compress(Bitmap.CompressFormat.JPEG, options, os);
}
}
// Generate compressed image file
FileOutputStream fos = new FileOutputStream(outPath);
fos.write(os.toByteArray());
Logger.getLogger().d("compressAndGenImage--->文件大卸膺丁:" + os.size()+"伦糯,壓縮比例:" + options);
fos.flush();
fos.close();
}
public static void compressAndGenImage(Bitmap image, String outPath) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
// scale
int options = 70;
// Store the bitmap into output stream(no compress)
image.compress(Bitmap.CompressFormat.JPEG, options, os);
// Generate compressed image file
FileOutputStream fos = new FileOutputStream(outPath);
fos.write(os.toByteArray());
Logger.getLogger().d("compressAndGenImage--->文件大小:" + os.size()+"嗽元,壓縮比例:" + options);
fos.flush();
fos.close();
}
喜歡的麻煩動動小手點個贊來支持我敛纲,有不對的地方歡迎大家指正,有什么問題也可以在下方留言剂癌,我看到后會第一時間回復(fù)淤翔!