前言
安卓的截图开发是一个很简单的功能,但是我的需求是在视频的过程中进行 截屏,如果普通截屏操作视频的部分会是黑色的,根本就不符合当前需求。所以记录下怎么能够截取视频画面。
点击截图按钮事件
MediaProjectionManager mMediaProjectionManager = null;
private int REQUEST_MEDIA_PROJECTION = 1;
startActivityForResult(
mMediaProjectionManager.createScreenCaptureIntent(),
REQUEST_MEDIA_PROJECTION);
回调监听
private String mImageName = "";
private MediaProjection mMediaProjection;
private VirtualDisplay mVirtualDisplay;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_MEDIA_PROJECTION) {
if (resultCode != Activity.RESULT_OK) {
Toast.makeText(this, "用户取消了", Toast.LENGTH_SHORT).show();
return;
}
final ImageReader mImageReader = ImageReader.newInstance(ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight(), 0x1, 2);
mMediaProjection = mMediaProjectionManager.getMediaProjection(resultCode, data);
mVirtualDisplay = mMediaProjection.createVirtualDisplay("ScreenCapture",
ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight(), getResources().getDisplayMetrics().densityDpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mImageReader.getSurface(), null, null);
mImageName = System.currentTimeMillis() + ".png";
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Image image = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
image = mImageReader.acquireLatestImage();
}
if (image == null) {
return;
}
int width = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
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 mBitmap;
mBitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
mBitmap.copyPixelsFromBuffer(buffer);
mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, width, height);
image.close();
if (mBitmap != null) {
//拿到mitmap
final Bitmap finalMBitmap = mBitmap;
}
}
}
}, 300);
}
}
网友评论