项目中有一个实现图片的剪切功能和APP“酷站”的点击中间“+”字符,进行图片选择到最后剪切功能;“微信”选择图片并剪切类似 ,由于测试的模拟器中没有图片,所以把参考资料上图片截下来展示下:
查了一些参考资料,使用的而并不是Android系统的图片剪切方法,而是UCrop库的封装,或自定义的高仿微信图片剪切:(请详细参考资料)
http://www.jb51.net/article/84434.htm
http://blog.csdn.net/fuchaosz/article/details/51202264
http://blog.csdn.net/liutaoblog/article/details/52452410
http://blog.csdn.net/maosidiaoxian/article/details/50828664
http://www.androidchina.net/4314.html
选择框实现:
xml布局:
public SelectPicturePopupWindow(Context context) {
super(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mMenuView = inflater.inflate(R.layout.layout_picture_selector, null);
takePhotoBtn = (Button) mMenuView.findViewById(R.id.picture_selector_take_photo_btn);
pickPictureBtn = (Button) mMenuView.findViewById(R.id.picture_selector_pick_picture_btn);
cancelBtn = (Button) mMenuView.findViewById(R.id.picture_selector_cancel_btn);
// 设置按钮监听
takePhotoBtn.setOnClickListener(this);
pickPictureBtn.setOnClickListener(this);
cancelBtn.setOnClickListener(this);
}
创建SelectPicturePopupWindow的时候设置按钮的监听。这里编写一个选择监听接口:
/**
* 选择监听接口
*/
public interface OnSelectedListener {
void OnSelected(View v, int position);
}
回调的参数为点击的按钮View以及当前按钮的索引,那么只要在选择监听里面返回接口的回调就可以啦。
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.picture_selector_take_photo_btn:
if(null != mOnSelectedListener) {
mOnSelectedListener.OnSelected(v, 0);
}
break;
case R.id.picture_selector_pick_picture_btn:
if(null != mOnSelectedListener) {
mOnSelectedListener.OnSelected(v, 1);
}
break;
case R.id.picture_selector_cancel_btn:
if(null != mOnSelectedListener) {
mOnSelectedListener.OnSelected(v, 2);
}
break;
}
}
PopupWindow的初始化创建、监听设置好之后,只要提供显示与隐藏两个方法就可以了。
/**
* 把一个View控件添加到PopupWindow上并且显示
*
* @param activity
*/
public void showPopupWindow(Activity activity) {
popupWindow = new PopupWindow(mMenuView, // 添加到popupWindow
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popupWindow.showAtLocation(activity.getWindow().getDecorView(), Gravity.CENTER | Gravity.BOTTOM, 0, 0);
popupWindow.setAnimationStyle(android.R.style.Animation_InputMethod); // 设置窗口显示的动画效果
popupWindow.setFocusable(false); // 点击其他地方隐藏键盘 popupWindow
popupWindow.update();
}
/**
* 移除PopupWindow
*/
public void dismissPopupWindow() {
if (popupWindow != null && popupWindow.isShowing()) {
popupWindow.dismiss();
popupWindow = null;
}
}
通过我们上面对选择框的封装,使用起来就比较简单了,只需要初始化及设置选择的监听就可以啦。
初始化选择框:
mSelectPicturePopupWindow = new SelectPicturePopupWindow(mContext);
mSelectPicturePopupWindow.setOnSelectedListener(this);
设置选择框的监听:
@Override
public void OnSelected(View v, int position) {
switch (position) {
case 0:
// TODO: "拍照"按钮被点击了
break;
case 1:
// TODO: "从相册选择"按钮被点击了
break;
case 2:
// TODO: "取消"按钮被点击了
break;
}
}
然后在Fragment上进行封装,我们取名为PictureSelectFragment。
拍照并保存图片
调用系统的拍照,并把拍摄的图片保存到指定位置。
@Override
public void OnSelected(View v, int position) {
switch (position) {
case 0:
// "拍照"按钮被点击了
mSelectPicturePopupWindow.dismissPopupWindow();
Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//下面这句指定调用相机拍照后的照片存储的路径
takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mTempPhotoPath)));
startActivityForResult(takeIntent, CAMERA_REQUEST_CODE);
break;
case 1:
// TODO: "从相册选择"按钮被点击了
break;
case 2:
// TODO: "取消"按钮被点击了
break;
}
}
这里的指定位置为sd卡本目录下
mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "photo.jpeg";
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == mActivity.RESULT_OK) {
switch (requestCode) {
case CAMERA_REQUEST_CODE:
// TODO: 调用相机拍照
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
调用系统的选择图片
@Override
public void OnSelected(View v, int position) {
switch (position) {
case 0:
// "拍照"按钮被点击了
mSelectPicturePopupWindow.dismissPopupWindow();
Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 下面这句指定调用相机拍照后的照片存储的路径
takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mTempPhotoPath)));
startActivityForResult(takeIntent, CAMERA_REQUEST_CODE);
break;
case 1:
// "从相册选择"按钮被点击了
mSelectPicturePopupWindow.dismissPopupWindow();
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);
break;
case 2:
// TODO: "取消"按钮被点击了
break;
}
}
当拍选择图片完成时会回调到onActivityResult,在这里处理选择的返回结果
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == mActivity.RESULT_OK) {
switch (requestCode) {
case CAMERA_REQUEST_CODE:
// TODO: 调用相机拍照
break;
case GALLERY_REQUEST_CODE:
// TODO: 直接从相册获取
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
使用Crop裁剪图片
裁剪图片,这里设置宽高比为1:1,最大尺寸为512*512,当然可以根据自己的需求来设置。
/**
* 裁剪图片方法实现
*
* @param uri
*/
public void startCropActivity(Uri uri) {
UCrop.of(uri, mDestinationUri)
.withAspectRatio(1, 1)
.withMaxResultSize(512, 512)
.withTargetActivity(CropActivity.class)
.start(mActivity, this);
}
当然,这里的比例你也可以设置成其他的,3:4 ,4:3 等等
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == mActivity.RESULT_OK) {
switch (requestCode) {
case CAMERA_REQUEST_CODE: // 调用相机拍照
File temp = new File(mTempPhotoPath);
startCropActivity(Uri.fromFile(temp));
break;
case GALLERY_REQUEST_CODE: // 直接从相册获取
startCropActivity(data.getData());
break;
case UCrop.REQUEST_CROP:
// TODO: 裁剪图片结果
break;
case UCrop.RESULT_ERROR:
// TODO: 裁剪图片错误
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
CropActivity的界面如下所示:
xml布局
代码片段:
@Override
protected void initViews() {
initToolBar();
mGestureCropImageView = mUCropView.getCropImageView();
mOverlayView = mUCropView.getOverlayView();
// 设置允许缩放
mGestureCropImageView.setScaleEnabled(true);
// 设置禁止旋转
mGestureCropImageView.setRotateEnabled(false);
// 设置外部阴影颜色
mOverlayView.setDimmedColor(Color.parseColor("#AA000000"));
// 设置周围阴影是否为椭圆(如果false则为矩形)
mOverlayView.setOvalDimmedLayer(false);
// 设置显示裁剪边框
mOverlayView.setShowCropFrame(true);
// 设置不显示裁剪网格
mOverlayView.setShowCropGrid(false);
final Intent intent = getIntent();
setImageData(intent);
}
private void setImageData(Intent intent) {
Uri inputUri = intent.getParcelableExtra(UCrop.EXTRA_INPUT_URI);
mOutputUri = intent.getParcelableExtra(UCrop.EXTRA_OUTPUT_URI);
if (inputUri != null && mOutputUri != null) {
try {
mGestureCropImageView.setImageUri(inputUri);
} catch (Exception e) {
setResultException(e);
finish();
}
} else {
setResultException(new NullPointerException("Both input and output Uri must be specified"));
finish();
}
// 设置裁剪宽高比
if (intent.getBooleanExtra(UCrop.EXTRA_ASPECT_RATIO_SET, false)) {
float aspectRatioX = intent.getFloatExtra(UCrop.EXTRA_ASPECT_RATIO_X, 0);
float aspectRatioY = intent.getFloatExtra(UCrop.EXTRA_ASPECT_RATIO_Y, 0);
if (aspectRatioX > 0 && aspectRatioY > 0) {
mGestureCropImageView.setTargetAspectRatio(aspectRatioX / aspectRatioY);
} else {
mGestureCropImageView.setTargetAspectRatio(CropImageView.SOURCE_IMAGE_ASPECT_RATIO);
}
}
// 设置裁剪的最大宽高
if (intent.getBooleanExtra(UCrop.EXTRA_MAX_SIZE_SET, false)) {
int maxSizeX = intent.getIntExtra(UCrop.EXTRA_MAX_SIZE_X, 0);
int maxSizeY = intent.getIntExtra(UCrop.EXTRA_MAX_SIZE_Y, 0);
if (maxSizeX > 0 && maxSizeY > 0) {
mGestureCropImageView.setMaxResultImageSizeX(maxSizeX);
mGestureCropImageView.setMaxResultImageSizeY(maxSizeY);
} else {
Log.w(TAG, "EXTRA_MAX_SIZE_X and EXTRA_MAX_SIZE_Y must be greater than 0");
}
}
}
以上为CropView的配置,更多配置请参考项目源码。
最重要的,裁剪保存图片:
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);
}
}
处理裁剪失败的返回值
/**
* 处理剪切失败的返回值
*
* @param result
*/
private void handleCropError(Intent result) {
deleteTempPhotoFile();
final Throwable cropError = UCrop.getError(result);
if (cropError != null) {
Log.e(TAG, "handleCropError: ", cropError);
Toast.makeText(mContext, cropError.getMessage(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, "无法剪切选择图片", Toast.LENGTH_SHORT).show();
}
}
这里设置了选择的回调接口,便于封装抽取。
/**
* 图片选择的回调接口
*/
public interface OnPictureSelectedListener {
/**
* 图片选择的监听回调
*
* @param fileUri
* @param bitmap
*/
void onPictureSelected(Uri fileUri, Bitmap bitmap);
}
我们的PictureSelectFragment就搞定了,在使用的时候只要继承它,几行代码就搞定了。
PictureSelectFragment使用
// 设置图片点击监听
mPictureIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectPicture();
}
});
// 设置裁剪图片结果监听
setOnPictureSelectedListener(new OnPictureSelectedListener() {
@Override
public void onPictureSelected(Uri fileUri, Bitmap bitmap) {
mPictureIv.setImageBitmap(bitmap);
String filePath = fileUri.getEncodedPath();
String imagePath = Uri.decode(filePath);
Toast.makeText(mContext, "图片已经保存到:" + imagePath, Toast.LENGTH_LONG).show();
}
});
源码:http://download.csdn.net/download/lijinweii/9945010