美文网首页
Android 5.0 屏幕录制/截屏

Android 5.0 屏幕录制/截屏

作者: Wang_Yi | 来源:发表于2018-01-24 17:50 被阅读179次

    Android 5.0之后的新API,平时很少用到这里记录下
    1. 获取系统服务

            mMediaProjectionManager = (MediaProjectionManager) getSystemService(
                    Context.MEDIA_PROJECTION_SERVICE);
            if (mMediaProjectionManager != null) {
                startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(),
                        200);
            }
    

    2. onActivityResult中获取MediaProjection

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == 200) {
                mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
            }
        }
    

    3.开始录制

        private void startCapture() {
            mMediaProjection.createVirtualDisplay(
                    "screen-mirror",
                    mSurfaceView.getWidth(),
                    mSurfaceView.getHeight(),
                    Resources.getSystem().getDisplayMetrics().densityDpi,
                    DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                    mSurfaceView.getHolder().getSurface(),
                    null,
                    null);
        }
    

    4.截屏

    1. 如果取余截屏的话我们要使用到ImageReader这个类,调用createVirtualDisplay:
        private void startCapture() {
            mImageReader = ImageReader.newInstance(mWindowWidth, mWindowHeight,
                    PixelFormat.RGBA_8888, 2);
            mMediaProjection.createVirtualDisplay(
                    "screen-mirror",
                    mWindowWidth,
                    mWindowHeight,
                    mScreenDensity,
                    DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                    mImageReader.getSurface(),
                    null,
                    null);
        }
    
    1. 截取Bitmap
        private Bitmap screenshot() {
            Image image = mImageReader.acquireLatestImage();
            int width = image.getWidth();
            int height = image.getHeight();
            Image.Plane[] planes = image.getPlanes();
            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();
            return bitmap;
        }
    

    相关文章

      网友评论

          本文标题:Android 5.0 屏幕录制/截屏

          本文链接:https://www.haomeiwen.com/subject/yaiuaxtx.html