运行图例:" />
当前位置: 代码迷 >> Android >> 运行图例:
  详细解决方案

运行图例:

热度:27   发布时间:2016-04-28 02:42:09.0
Android以当前Activity为基准进行截屏

概述:

    首先要知道在Android中截取图片大的方面可以分成两个方向,一个是走底层一点,一个是走上层。因为楼主底层代码比较弱,目前也只是停留在a+b的层面。所以,这篇博客只是在应用层上对屏幕进行一个截取。注意,上面讨论的两个方法与游戏中截图是两个概念,游戏中对屏幕的截取可以理解成一种假象。什么样的一种假象呢?没有截屏!因为玩游戏的时候,一般是全屏,这个时候只要保存内存中已经保存了的图像即可。

    对于应用层面的截图,它是基于Activity的。这里只是说是基于Activity,不是说一定是要由Activity来截图。那这句话不是矛盾了么?要怎么理解呢?例如,我现在想要截一张图,那我总得有一个截图的内容吧。就好像说我想把当前运行的程序给截个图,那么当前位于屏幕顶层的Activity就是这个内容了。这个我想要截一张图中的我则可以是Activity,也可以是Service,也可以是广播。


截图类代码:

下面大家可以看看已经封装好了的截图类的代码,如下:

public class ScreenShot {	// 获取指定Activity的截屏,保存到png文件	private static Bitmap takeScreenShot(Activity activity) {		// View是你需要截图的View		View view = activity.getWindow().getDecorView();		view.setDrawingCacheEnabled(true);		view.buildDrawingCache();		Bitmap bitmap = view.getDrawingCache();		// 获取状态栏高度		Rect frame = new Rect();		activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);		int statusBarHeight = frame.top;		System.out.println(statusBarHeight);		// 获取屏幕长和高		int width = activity.getWindowManager().getDefaultDisplay().getWidth();		int height = activity.getWindowManager().getDefaultDisplay().getHeight();		// 去掉标题栏		Bitmap b = Bitmap.createBitmap(bitmap, 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 activity) {		ScreenShot.savePic(ScreenShot.takeScreenShot(activity), "sdcard/apic/image" + System.currentTimeMillis() + ".png");	}}

上面的注释也留得相对详细,这里就不做过多说明了。说了也只是充字数,不必了。


使用示范:

ScreenShot.shoot(MainActivity.this);

运行图例:


<后续再更新另一种方法。。。>

  相关解决方案