Android裁剪图片(UCrop)使用说明
Android如何打开拍照 打开系统相册参考:
http://blog.youkuaiyun.com/weixin_37577039/article/details/79186183
使用的是UCrop的一个开源库
参考地址:https://github.com/Yalantis/uCrop
大致流程:
1 project gradle中
allprojects { repositories { jcenter() maven { url"https://jitpack.io"} }}
1
2
3
4
5
6
2 app gradle中添加依赖
compile'com.github.yalantis:ucrop:2.2.1'
1
最新版本参考github
3 权限配置
1
2
3
4 manifest.xml中配置
1
2
3
4
说明:
android:screenOrientation=”landscape”是限制此页面横屏显示,
android:screenOrientation=”portrait”是限制此页面数竖屏显示。
5 在拍照后的回传中设置
@OverridepublicvoidonActivityResult(intrequestCode,intresultCode, Intent data) { fragment4ImageView0 = findViewById(R.id.fragment4ImageView0);if(resultCode == MainActivity.RESULT_OK) {// 回传成功switch(requestCode) {// 选择请求码caseGlobalVariable.CAMERA_REQUEST_CODE: {try{// 裁剪startUCrop(); }catch(Exception e) { e.printStackTrace(); }break; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
6 在相册选择后的回传中设置
caseGlobalVariable.GALLERY_REQUEST_CODE: {// 获取图片try{ imageUri = data.getData();if(imageUri!=null) { startUCrop(); } }catch(Exceptione) { e.printStackTrace(); }break; }
1
2
3
4
5
6
7
8
9
10
11
12
7 设置Ucrop方法
private void startUCrop(){ //裁剪后保存到文件中 destinationUri = Uri.fromFile(new File(getCacheDir(),"myCroppedImage.jpg"));UCrop uCrop = UCrop.of(imageUri, destinationUri);UCrop.Optionsoptions = new UCrop.Options();//设置裁剪图片可操作的手势 options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);//设置toolbar颜色 options.setToolbarColor(ActivityCompat.getColor(this, R.color.orange2));//设置状态栏颜色 options.setStatusBarColor(ActivityCompat.getColor(this, R.color.orange2));//是否能调整裁剪框 // options.setFreeStyleCropEnabled(true);uCrop.withOptions(options);uCrop.start(this);}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
UCrop.of(imageUri, destinationUri) 原图片URI地址 生成图片的URI地址
8 设置UCrop回传 处理裁剪后的图片
caseUCrop.REQUEST_CROP: {// 裁剪照片finalUri croppedUri = UCrop.getOutput(data);try{if(croppedUri!=null) { Bitmap bit = BitmapFactory.decodeStream(getContentResolver().openInputStream(croppedUri)); fragment4ImageView0.setImageBitmap(bit); } }catch(Exceptione) { e.printStackTrace(); }break;}caseUCrop.RESULT_ERROR: {finalThrowable cropError = UCrop.getError(data); Log.i("RESULT_ERROR","UCrop_RESULT_ERROR");break;}
摘自:https://blog.youkuaiyun.com/weixin_37577039/article/details/79186862