最近研究了一些Android
的截屏方法,做一个总结。
图片剪裁方法
使用View.getDrawingCache()
得到Bitmap
。非常简单但是只能截图本应用的图片,并且没办法控制截图的范围。
对Bitmap
进行截屏。可以方便的操作截取大小,但是需要提前截取整个屏幕,然后再处理生成的Bitmap
。截取屏幕流程:打开一个新的Window
全屏展示,上面包含一个CropView
->操作CropView
选择区域->根据选择区域截取Bitmap
。
代码调用
一般需求用来从相册选择或者从相册发送图片。
(1).选择图片。打开系统选择图片的Activity
并设置相应的参数。
// 打开选择的Activity.
private void selectPic(){
Intent intent = new Intent("android.intent.action.PICK");
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, REQUEST_PICK_IMG);
}
(2).截切图片。选择图片成功(onActivityResult
)以后,设置相应参数开始裁剪图片。
// 截取图片
public void cutImage(Uri uri){
try {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", width);
intent.putExtra("outputY", height);
// 不返回bitmap,全使用uri来传递,防止图片使用内存太大
intent.putExtra("return-data", false);
intent.putExtra("output", outputUri);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("scale", true);
intent.putExtra("scaleUpIfNeeded", true);
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, REQUEST_CUT_IMG);
}
catch (Exception e) {
Log.e("Test", "com.android.camera.action.CROP error");
}
}
(3).onActivityResult
处理裁剪图片成功以后回调。
流程分析(基于api25
)
系统从相册打开图片,然后截取图片。源码在com.android.gallery3d
包下,com.android.gallery3d
是一个单独的应用(进程)。
(1).打开相册com.android.gallery3d/.app.GalleryActivity
,选择图片,略过。
(2).打开截图界面com.android.gallery3d/.filtershow.crop.CropActivity
。
(3).执行BitmapIOTask.doInBackground
,对sourceUri
进行操作,保存在dstUri
中。
(4).执行CropActivity.getCroppedImage
进行截图。
protected static Bitmap getCroppedImage(Bitmap image, RectF cropBounds, RectF photoBounds) {
// cropBounds:截取大小。photoBounds:图片大小。
RectF imageBounds = new RectF(0,