Android Picture trim Frame ucrop usage

Source: Internet
Author: User

1 Ucrop Introduction

The recent project used the picture clipping function, so Baidu a bit, found ucrop this frame, the frame of the star number, decided to use this framework

Ucrop's github address: Https://github.com/Yalantis/uCrop

Features of Ucrop:

    1. The cropping frame does not move, the picture moves
    2. The picture can be rotated, scaled
    3. Supports various proportional cropping boxes

Ucrop (from its github):

2 Integrated Ucrop

(1) Ucrop Integration method:

‘com.yalantis:ucrop:1.4.1‘

(2) Modify the current project's Build.gradle file, the modified code is as follows:

android {    23    "23.0.2"    defaultConfig {        "com.test"        15        23        1        "1.0"    }    ....}dependencies {    compile fileTree(dir‘libs‘, include: [‘*.jar‘])    ‘com.android.support:appcompat-v7:23.3.0‘    ‘com.yalantis:ucrop:1.4.1‘}

Note: After modifying the targetsdkversion, the COM.ANDROID.SUPPORT:APPCOMPAT-V7 version is also matched

Although the use of Maven dependencies, even if the APPCOMPAT-V7 version does not match, but the use of AAR files will be error, it is recommended that you modify the compilesdkversion also to modify the version of APPCOMPAT-V7, if you do not have a problem

(3) If you do not have 23 version of the SDK, that is, the Android 6.0 SDK, you want to launch the SDK manger to download, but also to download the Android SDK Build-tools 23.0.2, such as:

(4) Modify the version of the Gradle plugin
Modify the Gradle version of the entire project's outermost global Build.gradle file:

{        classpath ‘com.android.tools.build:gradle:2.0.0‘ }

(5) Download the latest Gradle

Gradle:http://services.gradle.org/distributions

Currently the latest version is gradle-2.13-rc-2-all.zip, unzip after download is complete, and then specify the address of Gradle in Android Studio, as shown in:

To use more than 2.0 versions of the Gradle plugin, you must use more than 2.10 gradle, note gradle plug-ins and gradle are two things, the former is Android studio plug-in, the latter is independent of things

(6) The completion of the preparation, synchronization code, Ucrop has been integrated into our project, is not very troublesome? Why else would I write this article?

Note: Ucrop must use version 23 and above Sdk,gradle plug-in version must be 2.0.0 and above, Gradle version must be 2.10 and above, appcompat-v7 version must be 23.0 and above

If the above are satisfied, it should not be an error. As for why the SDK is more than 23, because Ucrop uses the new features of Android 6.0: vectordrawable

3 Usage of Ucrop

(1) Add ucropactivity in Androidmanifest.xml, the code is as follows:

    <activity            android:name="com.yalantis.ucrop.UCropActivity"            android:screenOrientation="portrait"            android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

(2) Add Permissions in Androidmanifest.xml:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.INTERNET"/>

(3) The Mainactivity code is as follows:

 Public  class mainactivity extends Activity {Button btntest;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        btntest = (Button) Findviewbyid (r.id.btn_test); Btntest.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v)            {Startcrop ();    }        }); }Private void Startcrop() {Uri SourceUri = Uri.parse ("Http://star.xiziwang.net/uploads/allimg/140512/19_140512150412_1.jpg");//Save to file after croppingUri Destinationuri = Uri.fromfile (NewFile (Getcachedir (),"Samplecropimage.jpeg")); Ucrop.of (SourceUri, Destinationuri). Withaspectratio ( -,9). Withmaxresultsize ( -, -). Start ( This); }@Override    protected void Onactivityresult(intRequestcode,intResultCode, Intent data) {Super. Onactivityresult (Requestcode, ResultCode, data);if(ResultCode = = RESULT_OK) {//Cut Success            if(Requestcode = = Ucrop.request_crop) {Uri Croppedfileuri = ucrop.getoutput (data);//Get the default download directoryString Downloadsdirectorypath = environment.getexternalstoragepublicdirectory (environment.directory_downloads).                GetAbsolutePath (); String filename = String.Format ("%d_%s", Calendar.getinstance (). Gettimeinmillis (), croppedfileuri.getlastpathsegment ()); File SaveFile =NewFile (downloadsdirectorypath, filename);//Save the downloaded pictureFileInputStream instream =NULL; FileOutputStream OutStream =NULL; FileChannel Inchannel =NULL; FileChannel Outchannel =NULL;Try{instream =NewFileInputStream (NewFile (Croppedfileuri.getpath ())); OutStream =NewFileOutputStream (SaveFile);                    Inchannel = Instream.getchannel ();                    Outchannel = Outstream.getchannel (); Inchannel.transferto (0, Inchannel.size (), Outchannel); Toast.maketext ( This,"The cropped picture is guaranteed to exist:"+ Savefile.getabsolutepath (), Toast.length_short). Show (); }Catch(Exception e)                {E.printstacktrace (); }finally{Try{Outchannel.close ();                        Outstream.close ();                        Inchannel.close ();                    Instream.close (); }Catch(Exception e)                    {E.printstacktrace (); }                }            }        }//Trimming failed        if(ResultCode = = Ucrop.result_error) {Toast.maketext ( This,"crop picture failed", Toast.length_short). Show (); }    }}

The main interface layout\activity_main.xml on a button, do not post code
(4) method of calling Ucrop to cut

Uri sourceUri = Uri.parse("http://star.xiziwang.net/uploads/allimg/140512/19_140512150412_1.jpg");        //裁剪后保存到文件中        Uri destinationUri = Uri.fromFile"SampleCropImage.jpeg"));        UCrop.of(sourceUri, destinationUri).withAspectRatio(169).withMaxResultSize(300300).start(this);

In this example, a picture is downloaded from the web and saved to a local after cropping
(5) The image code after obtaining the cut is as follows

Cut Success if (Requestcode = = Ucrop. REQUEST_crop) {Uri Croppedfileuri = Ucrop. GetOutput(data);Get the default download directory String Downloadsdirectorypath = Environment. Getexternalstoragepublicdirectory(Environment. DIRECTORY_downloads). GetAbsolutePath();string filename = string. Format("%d_%s", Calendar. getinstance(). Gettimeinmillis(), Croppedfileuri. Getlastpathsegment());File SaveFile = new file (downloadsdirectorypath, filename);Save the downloaded picture FileInputStream instream = null;FileOutputStream OutStream = null;FileChannel Inchannel = null;FileChannel Outchannel = null;try {instream = new FileInputStream (The new File (Croppedfileuri. GetPath()));OutStream = new FileOutputStream (saveFile);Inchannel = instream. Getchannel();Outchannel = OutStream. Getchannel();Inchannel. TransferTo(0, Inchannel. Size(), Outchannel);Toast. Maketext(This,"The cropped picture is guaranteed to exist:"+ SaveFile. GetAbsolutePath(), Toast. LENGTH_short). Show();} catch (Exception e) {E. Printstacktrace();} finally {try {Outchannel. Close();OutStream. Close();Inchannel. Close();Instream. Close();} catch (Exception e) {E. Printstacktrace();}                }            }

Override the Onactivityresult () method to get the returned URI through data, and then take the trimmed file address from the URI and save it to the local

Note: To get the trimmed URI, you must use it Uri croppedFileUri = UCrop.getOutput(data) , you cannot use it, Uri uri = data.getData() or you will report a null pointer error

If trimming fails, the code is as follows:

 //裁切失败        if (resultCode == UCrop.RESULT_ERROR) {            Toast.makeText"裁切图片失败", Toast.LENGTH_SHORT).show();        }
4

5 issues encountered with AAR

Why use AAR files instead of maven dependencies, please refer to my blog:

[Android Studio Series (iii)] Android Studio compilation, synchronous slow resolution

How to download Ucrop Aar file also please refer to my above blog, currently download the latest Ucrop aar file is Ucrop-1.4.1.aar

If you use the Ucrop AAR file, you may experience the following problem:

The mistake of reading the newspaper carefully:

Error:(35forattribute‘srcCompatinpackage‘com.test3‘

Baidu took half a day, also did not find the reason, finally imitate Ucrop's demo modified APPCOMPAT-V7 version, solve the problem, after practice, APPCOMPAT-V7 should be modified as follows code:

‘com.android.support:appcompat-v7:23.3.0‘
6 other issues that may be encountered

(1) The SDK version is too low

Look carefully and find the following two mistakes:

Error: (2) Error retrieving parent for Item:no Resource found that matches the given name ' Android:TextAppearance.Material . Widget.Button.Inverse '.

Error: (2) Error retrieving parent for Item:no Resource found that matches the given name ' Android:Widget.Material.Button. Colored '.

The reason for reporting these two errors is that values-23 is a resource file in API (Android 6.0), which means that our SDK version is too low. looking at the example given by Ucrop, it is true that our version is too low, and the Build.gradle file address in the Ucrop example is as follows:

Https://github.com/Yalantis/uCrop/blob/master/sample/build.gradle

(2) Gradle plugin version is too low


Look carefully, error:

caused by:org.xmlpull.v1.XmlPullParserException:Binary XML file line #1: Invalid drawable tag vector
At Android.graphics.drawable.Drawable.createFromXmlInner (drawable.java:933)

If the SDK is already 23, run the times below the error, is the Gradle plug-in version does not reach 2.0 reasons, the workaround is:classpath ‘com.android.tools.build:gradle:2.0.0‘

(3) Gradle version too low

Look carefully, error:

Error:gradle version 2.10 is required. Current version is 2.8. If using the Gradle wrapper, try editing the Distributionurl in D:\AndroidStudioProjects\Hello7\gradle\wrapper\ Gradle-wrapper.properties to Gradle-2.10-all.zip
Fix Gradle Wrapper and Re-import project
Gradle settings

A look at the Gradle version is too low, follow the 2nd step to download the latest gradle, and then specify in Android Studio

(4) Improper introduction of ucropactivity results in Action Bar error

Look carefully, error:

caused By:java.lang.IllegalStateException:This Activity already has a action bar supplied by the window decor. Do not request Window.feature_support_action_bar and set Windowactionbar to False in your theme to use a Toolbar instead.

The reason is that when ucropactivity in Androidmanifest.xml, the android:theme="@style/Theme.AppCompat.Light.NoActionBar" correct introduction of the code is:

<activity            android:name="com.yalantis.ucrop.UCropActivity"            android:screenOrientation="portrait"            android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

Note: The last sentence cannot be dropped.

7 Summary

After some toss, finally put Ucrop, the project is still very new, using the Android 6.0 Victor Drawable, the code also used many new features of Android, such as: Comments @nonull, etc., it is worth to see the author's source code. After the explanation of this article, I believe you should have been happy to use the Ucrop, if you still encounter any problems, welcome to my message

8 reprint Please specify from "Indus Then Rain" blog: http://blog.csdn.net/fuchaosz/article/details/51202264

Tips
If you feel that this blog is helpful to you or like the blogger's writing style, give bloggers a message or the top of the chant, to encourage bloggers to make more quality blog, Thank you.

Android Picture trim Frame ucrop usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.