Android截屏保存png圖片的實(shí)例代碼
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
public class ScreenShot {
// 獲取指定Activity的截屏,保存到png文件
private static Bitmap takeScreenShot(Activity activity) {
// View是你需要截圖的View
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
// 獲取狀態(tài)欄高度
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
Log.i("TAG", "" + statusBarHeight);
// 獲取屏幕長和高
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay()
.getHeight();
// 去掉標(biāo)題欄
// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return b;
}
// 保存到sdcard
private static void savePic(Bitmap b, String strFileName) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(strFileName);
if (null != fos) {
b.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 程序入口
public static void shoot(Activity a) {
ScreenShot.savePic(ScreenShot.takeScreenShot(a), "sdcard/xx.png");
}
}
需要注意的是,shoot方法只能在view已經(jīng)被加載后方可調(diào)用。
或者在
@Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
ScreenShot.shoot(this);
}中調(diào)用
相關(guān)文章
在AndroidManifest.xml中uses-sdk內(nèi)屬性意思
本文為大家講解下minSdkVersion、targetSdkVersion、maxSdkVersion、target API level四個(gè)數(shù)值的意思與區(qū)別,感興趣的朋友可以參考下哈2013-06-06android studio 4.0 新建類沒有修飾符的方法
這篇文章主要介紹了android studio 4.0 新建類沒有修飾符的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10AndroidStudio Gradle基于友盟的多渠道打包方法
這篇文章主要介紹了AndroidStudio Gradle基于友盟的多渠道打包方法,需要的朋友可以參考下2017-09-09Android Studio 配置:自定義頭部代碼注釋及添加模版方式
這篇文章主要介紹了Android Studio 配置:自定義頭部代碼注釋及添加模版方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-03-03Android實(shí)現(xiàn)九宮格手勢(shì)密碼
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)九宮格手勢(shì)密碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06Fedora14下android開發(fā): eclipse與ibus確有沖突的問題分析
本篇文章是對(duì)Fedora14下android開發(fā),eclipse與ibus確有沖突的問題進(jìn)行了分析介紹,需要的朋友參考下2013-05-05