標籤:
今天項目裡要用到圖片的裁剪功能,本來想找第三方,但是查了下資料,覺得如果只是要簡單的實現其實也不難,所以決定自己寫一下
// 關於圖片的選擇 //點擊要選取圖片的view的時候要彈出兩個選項,拍照和選取本地- (void)addImageClick{ [_drawlineView removeFromSuperview]; // [self takePhotoAction]; UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"請選擇擷取方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet]; [actionSheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { // Cancel button tappped. [self dismissViewControllerAnimated:YES completion:^{ }]; }]]; [actionSheet addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { // 拍攝新照片 [self takePhotoAction]; }]]; [actionSheet addAction:[UIAlertAction actionWithTitle:@"從相簿選" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { // 從相片中讀取 [self browseAlbum]; }]]; [self presentViewController:actionSheet animated:YES completion:nil]; }//拍照//最好就是要判斷一下相機可不可用, allowsEditing是用來設定照片是否可以編輯,就是會不會出現一個框框來約束圖片的比例// sourceType 在拍照時用的 UIImagePickerControllerSourceTypeCamera 在選取圖片時用 UIImagePickerControllerSourceTypeSavedPhotosAlbum- (void)takePhotoAction { BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]; if (!isCamera) { //若不可用,彈出警告框 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"無可用網路攝影機" message:nil delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil]; [alert show]; return; } UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; imagePicker.allowsEditing = YES; imagePicker.delegate = self; [self presentViewController:imagePicker animated:YES completion:nil];}//不管拍照還是選取本地圖片,完成後都會調用這個方法//info 裡面放的圖片的所有資訊 UIImagePickerControllerOriginalImage這個key拿的是原圖 UIImagePickerControllerEditedImage拿的是圖片裁剪後的圖- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ NSString *mediaType = info[@"UIImagePickerControllerMediaType"]; if ([mediaType isEqualToString:@"public.image"]) { //判斷是否為圖片 UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];//這裡拿到圖片 //拿到圖片,你要做什麼事........ { //do something } //通過判斷picker的sourceType,如果是拍照則儲存到相簿去 if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) { UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil); } } }- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{ // Was there an error? if (error != NULL) { // Show error message... [WSToast showToastWithTitle:error.description duration:TOAST_VIEW_TIME completeCallBack:nil]; } else // No errors { // Show message image successfully saved [WSToast showToastWithTitle:@"圖片已儲存" duration:TOAST_VIEW_TIME completeCallBack:nil]; }}
WSToast 是我項目裡面封裝的提示展示框,當然,這隻是簡單的實現裁剪,裁剪的比例是固定不變的,而且也不能多選,就是簡單的需求而已
簡單的使用ios內建拍照裁剪功能