Today's apps are popular round heads, such as the top right corner of QQ head, the head of today's headlines and so on. This has become a trend in app design. Today we will simply implement this feature, and I will also store photos taken from my phone or gallery as avatars in the application sandbox.
The avatar will also be displayed the next time you enter the app.
The demo sample code is uploaded to: Https://github.com/chenyufeng1991/AvatarPhoto.
(1) The demo is implemented using storyboard. First drag a imageview to display the avatar and a button.
and drag it into the code to bind. Picture binding Iboutlet,button Binding ibaction. Storyboard design effects such as the following:
。
(2) Now to set the rectangle's ImageView as a circle, you can set the border color and width of the control at the same time.
Implementation code such as the following:
-(void) setcirclephoto{//avatarimage is a picture control; [Self.avatarImage.layer Setcornerradius:cgrectgetheight ([ Self.avatarimage bounds])/2]; Self.avatarImage.layer.masksToBounds = true; can set the border width, color self.avatarImage.layer.borderWidth = 1 according to the requirement; Self.avatarImage.layer.borderColor = [[Uicolor blackcolor] cgcolor]; Set the picture; self.avatarImage.layer.contents = (ID) [[UIImage imagenamed:@ "Avatar.png"] cgimage]; }
(3) The procedure is now implemented. Be able to find that the ImageView is already set to round.
The following will read the photos from your phone, by assuming that your device (real machine) supports taking pictures, the camera is turned on by default, and if your device does not support taking pictures (emulators), the gallery is opened by default. Implementations such as the following: Selectphoto is a click event for a button.
-(Ibaction) Selectphoto: (ID) Sender {if ([Self.imagepickerpopover ispopovervisible]) {[Self.imagepickerpopover di Smisspopoveranimated:yes]; Self.imagepickerpopover = nil; Return } Uiimagepickercontroller *imagepicker = [[Uiimagepickercontroller alloc] init]; imagepicker.editing = YES; Suppose the device supports the camera. Just use the camera technology//Otherwise let the user select photos from photo gallery if ([Uiimagepickercontroller issourcetypeavailable: Uiimagepickercontrollersourcetypecamera]) {imagepicker.sourcetype = Uiimagepickercontrollersourcetypecamera; } else{imagepicker.sourcetype = Uiimagepickercontrollersourcetypephotolibrary; } imagepicker.delegate = self; Agree to edit picture imagepicker.allowsediting = YES; Before creating a Uipopovercontroller object, check that the current device is not an ipad if ([uidevice currentdevice].userinterfaceidiom = = Uiuserinterfaceidiompad {self.imagepickerpopover = [[Uipopovercontroller alloc] initwithcontentviewcontroller:imagepicker]; Self.imagePickerPopover.delegate = self; [Self.imagepickerpopover PresentpopoverfrombarbuttOnitem:sender Permittedarrowdirections:uipopoverarrowdirectionany Animated:yes]; } else {[self presentviewcontroller:imagepicker animated:yes completion:nil]; }}-(void) Imagepickercontroller: (Uiimagepickercontroller *) Picker Didfinishpickingmediawithinfo: (NSDictionary< NSString *,id> *) info{//Get selected photos via info dictionary UIImage *image = [info valueforkey:uiimagepickercontrollereditedimage]; Use Itemkey as the key to save the photo in the Imagestore object [[Myimagestore Sharedstore] setimage:image forkey:@ "Cyfstore"]; Put the photo into the Uiimageview object self.avatarImage.image = image; Infers if the Uipopovercontroller object exists if (self.imagepickerpopover) {[Self.imagepickerpopover dismisspopoveranimated:yes]; Self.imagepickerpopover = nil; } else {//turns off Uiimagepickercontroller displayed in modal form [self dismissviewcontrolleranimated:yes completion:nil]; }}
(4) by executing the above procedure, you have been able to take photos from the camera or library and put them in the circular imageview. Let me explain the line of code above.
[[Myimagestore Sharedstore] setimage:image forkey:@ "Cyfstore"];
The line of code is to store the photo in the app sandbox, as well as by using key-value pairs.
The next time the program starts, it will read the picture directly.
Wait, I will come to realize this myimagestore class.
At the same time. Also declare a property:
@property (Strong, nonatomic) Uipopovercontroller *imagepickerpopover;
The Uipopovercontroller object is used to open the camera.
(5) The following will be implemented to store the picture in a sandbox (file storage) (more code.) Can directly refer to the source code)
+ (instancetype) sharedstore{static myimagestore *instance = nil; Ensure that only one object is created at a time in multi-threaded, thread-safe single-instance static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{instance = [[Self alloc] initprivate]; }); return instance;} -(instancetype) initprivate{self = [super init]; if (self) {_dictionary = [[Nsmutabledictionary alloc] init]; Register as a low memory notification viewer Nsnotificationcenter *NC = [Nsnotificationcenter defaultcenter]; [NC addobserver:self selector: @selector (clearcaches:) name:uiapplicationdidreceivememorywarningnot Ification Object:nil]; } return self;} -(void) SetImage: (UIImage *) image forkey: (NSString *) key{[self.dictionary setobject:image Forkey:key]; Gets the full path of the saved picture nsstring *path = [self imagepathforkey:key]; Extract JPEG data from the picture, the second parameter is the image compression reference NSData *data = uiimagejpegrepresentation (image, 0.5); Extract picture data in png format//nsdata *data = uiimagepngrepresentation (image); Write picture data to file [data Writetofile:path atomically:yes];} -(UIImage*) Imageforkey: (NSString *) key{//return [Self.dictionary Objectforkey:key]; UIImage *image = [Self.dictionary Objectforkey:key]; if (!image) {NSString *path = [self imagepathforkey:key]; Image = [UIImage Imagewithcontentsoffile:path]; if (image) {[Self.dictionary setobject:image forkey:key]; } else {NSLog (@ ' error:unable to find%@ ', [self imagepathforkey:key]); }} return image; -(NSString *) Imagepathforkey: (NSString *) key{Nsarray *documentdirectories = Nssearchpathfordirectoriesindomains ( NSDocumentDirectory, Nsuserdomainmask, YES); NSString *documentdirectory = [Documentdirectories firstobject]; return [Documentdirectory Stringbyappendingpathcomponent:key];} -(void) Clearcaches: (nsnotification *) n{NSLog (@ "Flushing%ld images out of the cache", (unsigned long) [Self.dictionary Co UNT]); [Self.dictionary removeallobjects];}
(6) Implementation of the program, the implementation of the results such as the following:
。
。
Summary, when the end of the selection of pictures, will be stored in the file, when the next time the program starts again, it will read the image from the file itself to display. In the actual development. The picture may have been obtained from the network. You will also be able to make a cache locally by uploading it to the server when you finish selecting the image. Improve efficiency.
The module can be extended and can be used directly in the project.
Blog UPDATE:
Let's say I don't want the image to be truncated and edited after it's taken, to set:
Imagepicker.allowsediting = false;
At the same time put:
Get selected photos via info dictionary UIImage *image = [info valueforkey:uiimagepickercontrollereditedimage];
Change to:
Get selected photos via info dictionary UIImage *image = [info valueforkey:uiimagepickercontrolleroriginalimage];
None of the above involves storing a picture on a mobile phone's library, the following method can save the image after the photo to the user's phone: the third parameter can write a callback method, that is, the image stored in the library after the method callback.
Save a photo to the gallery, whether the photo is taken by the camera or itself from the gallery, it will be saved to the gallery; uiimagewritetosavedphotosalbum (image, self, nil, nil);
Suppose we want to save a picture or use a network transmission. It is more appropriate to use NSData and compress:
Compress the picture, assuming the image to upload to the server or network, you need to run the step (compression), the second parameter is the compression scale, converted to NSData type. NSData *filedata = uiimagejpegrepresentation (image, 1.0);
Application Optimization and updates:
In fact, when the user chooses the picture, the user should also choose whether to open the camera or the library.
The following code optimization is the pop-up selection box (Uialertcontroller), which is primarily the setting of the SourceType property. Now click the button's event handling changes such as the following: Code updates have been submitted to: Https://github.com/chenyufeng1991/AvatarPhoto.
-(Ibaction) Selectphoto: (ID) Sender {if ([Self.imagepickerpopover ispopovervisible]) {[Self.imagepickerpopover Dismis Spopoveranimated:yes]; Self.imagepickerpopover = nil; Return } Uiimagepickercontroller *imagepicker = [[Uiimagepickercontroller alloc] init]; imagepicker.editing = YES; Imagepicker.delegate = self; /* Suppose the allowsediting here is set to false. Then the following uiimage *image = [info valueforkey:uiimagepickercontrollereditedimage]; Should read: UIImage *image = [info valueforkey:uiimagepickercontrolleroriginalimage]; The original image is changed. Instead of the edited image. *//Agree to edit picture imagepicker.allowsediting = YES; /* Here is a pop-up selection box to let the user choose whether to open the camera or the gallery *//Initialize the prompt box. Uialertcontroller *alert = [Uialertcontroller alertcontrollerwithtitle:@ "Please select Open with" Message:nil PreferredStyle: Uialertcontrollerstyleactionsheet]; [Alert addaction:[uialertaction actionwithtitle:@ "Camera" Style:uialertactionstyledefault handler:^ (UIAlertAction * _ Nonnull action) {imagepicker.sourcetype = uiimagepickercontrollersourcetypecamera;//set to camera open;//Create Uipopovercontroll The ER object is checked before the current device is not the ipad if ([uidevice currentdevice].userinterfaceidiom = = Uiuserinterfaceidiompad) {Self.imagepicker Popover = [[Uipopovercontroller alloc] initwithcontentviewcontroller:imagepicker]; Self.imagePickerPopover.delegate = self; [Self.imagepickerpopover Presentpopoverfrombarbuttonitem:sender Permittedarrowdirecti Ons:uipopoverarrowdirectionany Animated:yes]; } else{[Self PresentviewconTroller:imagepicker Animated:yes Completion:nil]; } }]]; [Alert addaction:[uialertaction actionwithtitle:@ ' register ' style:uialertactionstyledefault handler:^ (UIAlertAction * _ Nonnull action) {imagepicker.sourcetype = uiimagepickercontrollersourcetypephotolibrary;//set to Gallery open. Before creating a Uipopovercontroller object, check that the current device is not an ipad if ([uidevice currentdevice].userinterfaceidiom = = Uiuserinterfaceidiompad {self.imagepickerpopover = [[Uipopovercontroller alloc] initwithcontentviewcontroller:imagepicker]; Self.imagePickerPopover.delegate = self; [Self.imagepickerpopover Presentpopoverfrombarbuttonitem:sender Permittedarrowdirecti Ons:uipopoverarrowdirectionany Animated:yes]; } else{[self Presentviewcontroller:imagepicker animated:yes completion:nil]; } }]]; [Alert addaction:[uialertaction actionwithtitle:@ "Cancel" style:uialertactionstyledestructive handler:^ (UIAlertAction * _nonNull action) {//Cancel;}]]; Popup notification box; [self Presentviewcontroller:alert animated:true completion:nil];}
Implementation effects such as the following:
GitHub Home:https://github.com/chenyufeng1991 .
Welcome to visit us!
iOS development-Customizing the use of circular avatars and camera libraries