Android截屏保存png图片的实例代码
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();
// 获取状态栏高度
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();
// 去掉标题栏
// 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已经被加载后方可调用。
或者在
@override
public void onwindowfocuschanged(boolean hasfocus) {
// todo auto-generated method stub
super.onwindowfocuschanged(hasfocus);
screenshot.shoot(this);
}中调用