標籤:使用 alt 啟動 jpg 儲存 cat tick tco pen
最近利用一周左右的業餘時間,終於完成了一個Android圖片剪裁庫,核心功能是根據自己的理解實現的,部分代碼參考了Android源碼的圖片剪裁應用。現在將該代碼開源在Github上以供大家學習和使用,地址:https://github.com/Jhuster/ImageCropper,效果如下所示:
我的大致計劃是首先介紹一下這個庫的用法,然後再寫幾篇文章介紹一下其中的一些原理和關鍵技術,希望對Android開發新手有所協助。
【特性】
支援通過手勢移動和縮放剪裁視窗
支援固定剪裁視窗大小、固定視窗的長寬比率
支援設定最大的視窗長和寬
支援剪裁圖片的旋轉
易於整合和使用
【使用方法】
修改AndroidManifest.xml檔案
<activity android:name="com.ticktick.imagecropper.CropImageActivity"/>
需要添加寫SDcard的許可權
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2. 啟動圖片剪裁介面的方法
第一種方法,使用庫中封裝的CropIntent來構建Intent對象:
private void startCropImage() { // Create a CropIntent CropIntent intent = new CropIntent(); // Set the source image filepath/URL and output filepath/URL (Required) intent.setImagePath("/sdcard/source.jpg"); intent.setOutputPath("/sdcard/cropped.jpg"); // Set a fixed crop window size (Optional) intent.setOutputSize(640,480); // Set the max crop window size (Optional) intent.setMaxOutputSize(800,600); // Set a fixed crop window‘s width/height aspect (Optional) intent.setAspect(3,2); // Start ImageCropper activity with certain request code and listen for result startActivityForResult(intent.getIntent(this), REQUEST_CODE_CROP_PICTURE);}
第二種方法,自訂Intent對象:
private void startCropImage() { // Create explicit intent Intent intent = new Intent(this, CropImageActivity.class); // Set the source image filepath/URL and output filepath/URL (Required) intent.setData(Uri.fromFile(new File("/sdcard/source.jpg"))); intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File("/sdcard/cropped.jpg"))); // Set a fixed crop window size (Optional) intent.putExtra("outputX",640); intent.putExtra("outputY",480); // Set the max crop window size (Optional) intent.putExtra("maxOutputX",800); intent.putExtra("maxOutputY",600); // Set a fixed crop window‘s width/height aspect (Optional) intent.putExtra("aspectX",3); intent.putExtra("aspectY",2); // Start ImageCropper activity with certain request code and listen for result startActivityForResult(intent, REQUEST_CODE_CROP_PICTURE);}
3. 擷取剪裁結果
剪裁結束後,如果使用者點擊了“Save”按鈕,則可以通過MediaStore.EXTRA_OUTPUT得到儲存的圖片的URL地址;如果使用者點擊了“Cancel”,則Activity的傳回值會被設定為 RESULT_CANCEL
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { return; } if (requestCode == REQUEST_CODE_CROP_PICTURE ) { Uri croppedUri = data.getExtras().getParcelable(MediaStore.EXTRA_OUTPUT); InputStream in = null; try { in = getContentResolver().openInputStream(croppedUri); Bitmap b = BitmapFactory.decodeStream(in); mImageView.setImageBitmap(b); } catch (FileNotFoundException e) { e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data);}
Android圖片剪裁庫