我的开源项目:Android图片剪裁库
最近利用一周左右的业余时间,终于完成了一个Android图片剪裁库,核心功能是根据自己的理解实现的,部分代码参考了Android源码的图片剪裁应用。现在将该代码开源在Github上以供大家学习和使用,地址:https://github.com/Jhuster/ImageCropper,效果如下所示:
我的大致计划是首先介绍一下这个库的用法,然后再写几篇文章介绍一下其中的一些原理和关键技术,希望对Android开发新手有所帮助。
【特性】
支持通过手势移动和缩放剪裁窗口
支持固定剪裁窗口大小、固定窗口的长宽比率
支持设置最大的窗口长和宽
支持剪裁图片的旋转
易于集成和使用
【使用方法】
修改AndroidManifest.xml文件
需要添加一个Activity标签:
<activityandroid:name="com.ticktick.p_w_picpathcropper.CropImageActivity"/>
需要添加写SDcard的权限
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2. 启动图片剪裁界面的方法
第一种方法,使用库中封装的CropIntent来构建Intent对象:
privatevoidstartCropImage(){//CreateaCropIntentCropIntentintent=newCropIntent();//Setthesourcep_w_picpathfilepath/URLandoutputfilepath/URL(Required)intent.setImagePath("/sdcard/source.jpg");intent.setOutputPath("/sdcard/cropped.jpg");//Setafixedcropwindowsize(Optional)intent.setOutputSize(640,480);//Setthemaxcropwindowsize(Optional)intent.setMaxOutputSize(800,600);//Setafixedcropwindow'swidth/heightaspect(Optional)intent.setAspect(3,2);//StartImageCropperactivitywithcertainrequestcodeandlistenforresultstartActivityForResult(intent.getIntent(this),REQUEST_CODE_CROP_PICTURE);}
第二种方法,自定义Intent对象:
privatevoidstartCropImage(){//CreateexplicitintentIntentintent=newIntent(this,CropImageActivity.class);//Setthesourcep_w_picpathfilepath/URLandoutputfilepath/URL(Required)intent.setData(Uri.fromFile(newFile("/sdcard/source.jpg")));intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(newFile("/sdcard/cropped.jpg")));//Setafixedcropwindowsize(Optional)intent.putExtra("outputX",640);intent.putExtra("outputY",480);//Setthemaxcropwindowsize(Optional)intent.putExtra("maxOutputX",800);intent.putExtra("maxOutputY",600);//Setafixedcropwindow'swidth/heightaspect(Optional)intent.putExtra("aspectX",3);intent.putExtra("aspectY",2);//StartImageCropperactivitywithcertainrequestcodeandlistenforresultstartActivityForResult(intent,REQUEST_CODE_CROP_PICTURE);}
3. 获取剪裁结果
剪裁结束后,如果用户点击了“Save”按钮,则可以通过MediaStore.EXTRA_OUTPUT得到保存的图片的URL地址;如果用户点击了“Cancel”,则Activity的返回值会被设置为 RESULT_CANCEL
protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){if(resultCode!=RESULT_OK){return;}if(requestCode==REQUEST_CODE_CROP_PICTURE){UricroppedUri=data.getExtras().getParcelable(MediaStore.EXTRA_OUTPUT);InputStreamin=null;try{in=getContentResolver().openInputStream(croppedUri);Bitmapb=BitmapFactory.decodeStream(in);mImageView.setImageBitmap(b);}catch(FileNotFoundExceptione){e.printStackTrace();}}super.onActivityResult(requestCode,resultCode,data);}
【小结】
这个库就先介绍到这里,有任何疑问欢迎留言或者来信lujun.hust@gmail.com交流,也欢迎大家提出意见和建议,或者为该开源代码做出自己的贡献,谢谢。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。