1
我正在使用以下代碼來獲取屏幕截圖。我得到了屏幕截圖,但是圖像上附有黑色填充。代碼示例在互聯網上找到屏幕截圖和刪除填充用於這裏:使用MediaProjection API進行屏幕截圖時的額外填充
// requesting permission
MediaProjectionManager projectionManager = (MediaProjectionManager) getSystemService(
Context.MEDIA_PROJECTION_SERVICE);
startActivityForResult(projectionManager.createScreenCaptureIntent(), REQUEST_SCREENSHOT);
// requesting screenshot on successful permission (in onActivityResult)
if (requestCode == REQUEST_SCREENSHOT && resultCode == RESULT_OK) {
MediaProjectionManager projectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
final MediaProjection mProjection = projectionManager.getMediaProjection(resultCode, data);
Display mDisplay = getWindowManager().getDefaultDisplay();
Point size = new Point();
mDisplay.getSize(size);
final int width = size.x;
final int height = size.y;
final ImageReader mImageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2);
mProjection.createVirtualDisplay("screen-mirror", width, height,
getResources().getDisplayMetrics().densityDpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY |
DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC, mImageReader.getSurface(),
null, null);
mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
@Override
public void onImageAvailable(ImageReader imageReader) {
final Image image = imageReader.acquireLatestImage();
if (image != null) {
mImageReader.setOnImageAvailableListener(null, null);
mProjection.stop();
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;
// create bitmap
Bitmap bmp = Bitmap.createBitmap(
width + rowPadding/pixelStride, height, Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buffer);
image.close();
ImageView iv = findViewById(R.id.iv);
iv.setImageBitmap(bmp);
}
}
}, null);
}
這裏是一個屏幕截圖,顯示我所得到的。我在我的Activity中將位圖加載到ImageView中。
這工作完全得到位另一個位圖的基礎上,但我可以做到這一點使用一個位圖?性能對於我的應用程序的使用非常重要,我注意到創建兩個位圖需要更多時間。 – Usman
我想,沒有辦法使用一個位圖。如果要將位圖設置爲ImageView,則可以將ImageView比率(width:height)設置爲mWidth/mHeight,將scaleType設置爲fitStart –