第一步:引入 compile('com.kevin:crop:1.0.2') { exclude group: 'com.android.support', module: 'appcompat-v7' }
第二步:检查拍照,写入权限;
第三步:
1.拍照:Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //下面这句指定调用相机拍照后的照片存储的路径 takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mTempPhotoPath))); startActivityForResult(takeIntent, CAMERA_REQUEST_CODE);
2.相册:Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
// 如果限制上传到服务器的图片类型时可以直接写如:"image/jpeg 、 image/png等的类型" pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(pickIntent, GALLERY_REQUEST_CODE);
第四步:跳转的CropActivity
UCrop.of(uri, mDestinationUri) .withAspectRatio(1, 1) .withMaxResultSize(300, 300) .withTargetActivity(CropActivity.class) .start(mActivity, this);
第五步:CropActivity关键代码
// 设置允许缩放 mGestureCropImageView.setScaleEnabled(true); // 设置禁止旋转 mGestureCropImageView.setRotateEnabled(false); // 设置外部阴影颜色 mOverlayView.setDimmedColor(Color.parseColor("#AA000000")); // 设置周围阴影是否为椭圆(如果false则为矩形) mOverlayView.setOvalDimmedLayer(false); // 设置显示裁剪边框 mOverlayView.setShowCropFrame(true); // 设置不显示裁剪网格 mOverlayView.setShowCropGrid(false);
private void cropAndSaveImage() { OutputStream outputStream = null; try { final Bitmap croppedBitmap = mGestureCropImageView.cropImage(); if (croppedBitmap != null) { outputStream = getContentResolver().openOutputStream(mOutputUri); croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream); croppedBitmap.recycle(); setResultUri(mOutputUri, mGestureCropImageView.getTargetAspectRatio()); finish(); } else { setResultException(new NullPointerException("CropImageView.cropImage() returned null.")); } } catch (Exception e) { setResultException(e); finish(); } finally { BitmapLoadUtils.close(outputStream); } }
private TransformImageView.TransformImageListener mImageListener = new TransformImageView.TransformImageListener() { @Override public void onRotate(float currentAngle) { } @Override public void onScale(float currentScale) { } @Override public void onLoadComplete() { Animation fadeInAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.in_left_right); fadeInAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { mUCropView.setVisibility(View.VISIBLE); mGestureCropImageView.setImageToWrapCropBounds(); } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }); mUCropView.startAnimation(fadeInAnimation); } @Override public void onLoadFailure(Exception e) { setResultException(e); finish(); } };