上周做了一个头像主要是为了抽出来封装一下,因为99%的应用都需要个人头像的上进行裁剪然后作为头像.所以考虑到这部分的需求,所以要解耦,为了代码的阅读性,扩展性等.
大家都知道调用系统相机和相册都会运用OnActivityResult方法来获取操作和数据.那么需要对这个函数进行良好的编码.
首先启动一个Activity需要调用ActivityForResult然后RequestCode必须要与CallBack一致这样才能执行指定的方法,其次5.0中裁剪后resultCode并不是默认,变成了2,所以需要判断版本.下面我们看一下Activity的CallBack方法:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d("Tanck", "requestCode:" + requestCode + "----" + "resultCode:" + resultCode); //响应成功 if (MainActivity.RESULT_OK != resultCode && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) return; switch (requestCode) { case IMG_OPTION:// option //5.0+兼容 if (null == data) return; int code = data.getIntExtra(SelectPicPopupWindow.IMG_KEY, 0); switch (code) { case SelectPicPopupWindow.TAKE_PHONE: // 照相机 Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); camera.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(camera, CAMERA_REQUEST_CODE); return; case SelectPicPopupWindow.PICK_PHONE:// 图库 Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); gallery.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(gallery, GALLERY_REQUEST_CODE); return; } break; case CAMERA_REQUEST_CODE://拍照请求裁剪 startPhotoZoom(uri); break; case PHOTO_REQUEST_CUT://设置裁剪后最后结果图片 Bitmap head = data.getParcelableExtra("data"); Log.d("Tanck", "head:" + head); if (null == head) return; mHead.setImageBitmap(head); break; case GALLERY_REQUEST_CODE://相册请求裁剪 //5.0+兼容 if (null == data) return; Uri galleryUri = data.getData(); startPhotoZoom(galleryUri); break; } }
下面是裁剪的方法,裁剪需要设置裁剪比例,根据自己的需求去设置:
/** * 图片处理 * * @param uri */ private void startPhotoZoom(Uri uri) { 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", 200); intent.putExtra("outputY", 200); intent.putExtra("return-data", true); intent.putExtra("output", uri); intent.putExtra("outputFormat", "JPEG"); startActivityForResult(intent, PHOTO_REQUEST_CUT); }