對屏幕進行截屏並裁剪有兩種方式:早截圖和晚截圖。早截圖,就是先截取全屏,再讓用戶對截取到的圖片進行修改;與之相對的,晚截圖,就是先讓用戶在屏幕上劃好區域,再進行截圖和裁剪。其實兩者並沒有什麼太大的區別,這篇就說說怎麼實現晚截圖。
晚截圖可以分成三步:
1. 在屏幕上標出截圖的矩形區域
2. 調用系統接口截屏
3. 對截圖進行裁剪
效果圖如下:
第一步、在屏幕上標識出截圖區域
首先確定標識截圖區域所需要的功能:
1. 手指拖動形成矩形區域;
2. 可以拖動已經劃好的矩形區域進行移動;
3. 可以拖動矩形區域的邊框調整大小;
4. 選擇完成以後,有“確認”和“取消”功能,“確認”時可以獲得選取的區域位置。需要注意的是,按鈕的位置應該能夠自適應,比如選框幾乎占據全屏的情況下,應該把按鈕放到選框內部。
最簡單的方式就是寫一個自定義View,根據touch的位置執行不同的功能即可。實現很簡單,只要細心把每一種狀態就行,代碼請看Bigbang項目的MarkSizeView類。
第二步、調用系統接口截屏
截屏必須在Activity中進行,因為需要調用startActivityForResult()。不過也可以把mMediaProjectionManager傳到service中進行後續處理。
還要注意的是Activity本身在截屏的時候應該是透明的,不能對要截取得內容有影響。
直接看代碼:
public class ScreenCaptureActivity extends Activity { private static final String TAG = ScreenCaptureActivity.class.getName(); private MediaProjectionManager mMediaProjectionManager; private int REQUEST_MEDIA_PROJECTION = 1; private SimpleDateFormat dateFormat; private String pathImage; private WindowManager mWindowManager; private ImageReader mImageReader; private MediaProjection mMediaProjection; private int mResultCode; private Intent mResultData; private VirtualDisplay mVirtualDisplay; private String strDate; private int windowWidth; private int windowHeight; private String nameImage; private int mScreenDensity; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mMediaProjectionManager = (MediaProjectionManager) getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE); createVirtualEnvironment(); startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_MEDIA_PROJECTION) { if (resultCode != Activity.RESULT_OK) { return; } else if (data != null && resultCode != 0) { mResultCode = resultCode; mResultData = data; startVirtual(); new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { startCapture(); } },100); } } } @RequiresApi(api = Build.VERSION_CODES.KITKAT) private void createVirtualEnvironment() { dateFormat = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss"); strDate = dateFormat.format(new Date()); pathImage = Environment.getExternalStorageDirectory().getPath() + "/Pictures/"; nameImage = pathImage + strDate + ".png"; mMediaProjectionManager = (MediaProjectionManager) getApplication().getSystemService(Context.MEDIA_PROJECTION_SERVICE); mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE); windowWidth = mWindowManager.getDefaultDisplay().getWidth(); windowHeight = mWindowManager.getDefaultDisplay().getHeight(); DisplayMetrics metrics = new DisplayMetrics(); mWindowManager.getDefaultDisplay().getMetrics(metrics); mScreenDensity = metrics.densityDpi; mImageReader = ImageReader.newInstance(windowWidth, windowHeight, 0x1, 2); //ImageFormat.RGB_565 Log.i(TAG, "prepared the virtual environment"); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public void startVirtual() { if (mMediaProjection != null) { Log.i(TAG, "want to display virtual"); virtualDisplay(); } else { Log.i(TAG, "start screen capture intent"); Log.i(TAG, "want to build mediaprojection and display virtual"); setUpMediaProjection(); virtualDisplay(); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public void setUpMediaProjection() { mMediaProjection = mMediaProjectionManager.getMediaProjection(mResultCode, mResultData); Log.i(TAG, "mMediaProjection defined"); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void virtualDisplay() { mVirtualDisplay = mMediaProjection.createVirtualDisplay("screen-mirror", windowWidth, windowHeight, mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null); Log.i(TAG, "virtual displayed"); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void startCapture() { strDate = dateFormat.format(new java.util.Date()); nameImage = pathImage + strDate + ".png"; Image image = mImageReader.acquireLatestImage(); int width = image.getWidth(); int height = image.getHeight(); final Image.Plane[] planes = image.getPlanes(); final ByteBuffer buffer = planes[0].getBuffer(); int pixelStride = planes[0].getPixelStride(); int rowStride = planes[0].getRowStride(); int rowPadding = rowStride - pixelStride * width; Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888); bitmap.copyPixelsFromBuffer(buffer); bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height); image.close(); Log.i(TAG, "image data captured"); //保存截屏結果,如果要裁剪圖片,在這裡處理bitmap if (bitmap != null) { try { File fileImage = new File(nameImage); if (!fileImage.exists()) { fileImage.createNewFile(); Log.i(TAG, "image file created"); } FileOutputStream out = new FileOutputStream(fileImage); if (out != null) { bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); Intent media = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri contentUri = Uri.fromFile(fileImage); media.setData(contentUri); this.sendBroadcast(media); Log.i(TAG, "screen image saved"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void tearDownMediaProjection() { if (mMediaProjection != null) { mMediaProjection.stop(); mMediaProjection = null; } Log.i(TAG, "mMediaProjection undefined"); } }
第三步、對截圖進行裁剪
根據第一步得到的截圖區域mRect對第二步中得到的截屏結果bitmap進行裁剪:
if (mRect != null) { if (mRect.left < 0) mRect.left = 0; if (mRect.right < 0) mRect.right = 0; if (mRect.top < 0) mRect.top = 0; if (mRect.bottom < 0) mRect.bottom = 0; int cut_width = Math.abs(mRect.left - mRect.right); int cut_height = Math.abs(mRect.top - mRect.bottom); if (cut_width > 0 && cut_height > 0) { Bitmap cutBitmap = Bitmap.createBitmap(bitmap, mRect.left, mRect.top, cut_width, cut_height); }
需要注意的是,在調用系統截屏功能的時候,如果手機有NavigationBar(虛擬導航欄),windowHeight的取值就是不包括NavigationBar的高度的,如果不進行調整,就會導致截屏被壓縮。如何獲取屏幕的真實高度,可以參考Android如何判斷NavigationBar是否顯示(獲取屏幕真實的高度)。
而且NavigationBar還會導致截屏的結果出現邊框,邊框的顏色是透明的,原因是第二步代碼中的rowPadding!=0,截屏如下圖所示:
那麼如果我們想要對截圖的結果進行保存或者裁剪,就必須要去除邊框,找出真正的內容區域,也就是在第一個不透明的像素和最後一個不透明像素之間的內容,然後才能對得到的區域進行第三步的裁剪,代碼如下:
int[] pixel=new int[width]; bitmap.getPixels(pixel,0,width ,0,0,width,1); int leftPadding=0; int rightPadding=width; for (int i=0;i<pixel.length;i++){ if (pixel[i]!=0){ leftPadding=i; break; } } for (int i=pixel.length-1;i>=0;i--){ if (pixel[i]!=0){ rightPadding=i; break; } } bitmap=Bitmap.createBitmap(bitmap,leftPadding, 0, rightPadding-leftPadding, height);
處理後的截圖如下:
你可能會覺得既然是rowPadding!=0導致出現邊框,而且邊框只在右邊,為什麼不直接把右邊rowPadding寬度的內容截掉呢?其實是因為如果不調整windowHeight,就會在左邊也產生框,所以才用了上面的方法。
完整代碼可以參考Bigbang項目的MarkSizeView類、ScreenCaptureActivity類和ScreenCapture類。