Android 把视图转换为图片,截取屏幕

来源:互联网 发布:蓝色妖姬 js特效 编辑:程序博客网 时间:2024/05/17 09:33



一、先来看看如何把视图转换为图片

view.setDrawingCacheEnabled(true);Bitmap viewBitmap = view.getDrawingCache();view.setDrawingCacheEnabled(false);

View对象自身支持此功能



二、截取屏幕

先开看看Activity,一个截屏按钮,当点击时把图片保存到当前项目的/data/data目录下

public class MainActivity extends Activity {private static final String FILE_NAME = "ScreenShot";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                Button button = (Button) findViewById(R.id.button_screen_shot);button.setText("截屏");button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 获取保存路径String filePath = getSavePath();// 截取屏幕为Bitmap格式Bitmap bitmap = takeScreenShot();// 保存截图到手机if (filePath != null) {savePic( bitmap,  filePath );}}});    }}

获取保存图片的路径

/** * 获取保存路径 *  */private String getSavePath() {File filesDir = getFilesDir(); if (filesDir != null) {// data/data/com.tom/filesreturn filesDir.getParent() + "/" + filesDir.getName() + "/"+ FILE_NAME +".png";}return null;}


当前屏幕出去状态栏视图转换为bitmap格式

/** * 获取屏幕bitmap对象 *  * @return */private Bitmap takeScreenShot() {// View是你需要截图的ViewView view = getWindow().getDecorView();view.setDrawingCacheEnabled(true);view.buildDrawingCache();Bitmap obtainBitmap = view.getDrawingCache();// 获取状态栏高度Rect frame = new Rect();getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);int statusBarHeight = frame.top;// 获取屏幕长和高int width = getWindowManager().getDefaultDisplay().getWidth();int height = getWindowManager().getDefaultDisplay().getHeight();// 截取当前屏幕,去掉标题栏 Bitmap bitmap = Bitmap.createBitmap(obtainBitmap, 0, statusBarHeight, width, height- statusBarHeight);view.destroyDrawingCache();view.setDrawingCacheEnabled(false);return bitmap;} 


图片保存到指定目录

/** * 保存图片 *  * @param b * @param strFileName */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();}}