詳解iOS 裁剪圓形圖像并顯示(類似于微信頭像)
本文主要講解如何從照片庫選擇一張照片后將其裁剪成圓形頭像并顯示,類似于微信頭像那種模式。
本文的方法也適用于當時拍照獲取的圖像,方法類似,所以不再贅述。
本文主要是在iOS 10環(huán)境下使用,此時如果要使用使用系統照片庫、照相機等功能需要授權,授權方法如下:
右鍵點擊工程目錄中的“Info.plist文件——>Open As ——>Source Code”,打開復制以下你在應用中使用的隱私權限設置(描述自己修改):
<key>NSVideoSubscriberAccountUsageDescription</key> <string></string> <key>NSBluetoothPeripheralUsageDescription</key> <string>藍牙權限</string> <key>NSSpeechRecognitionUsageDescription</key> <string>語音識別權限</string> <key>NSSiriUsageDescription</key> <string>Siri權限</string> <key>NSRemindersUsageDescription</key> <string></string> <key>NSPhotoLibraryUsageDescription</key> <string>相冊權限</string> <key>kTCCServiceMediaLibrary</key> <string></string> <key>NSMotionUsageDescription</key> <string>運動權限</string> <key>NSMicrophoneUsageDescription</key> <string>麥克風權限</string> <key>NSAppleMusicUsageDescription</key> <string>音樂權限</string> <key>NSLocationWhenInUseUsageDescription</key> <string>地理位置權限</string> <key>NSLocationUsageDescription</key> <string>地理位置權限</string> <key>NSLocationAlwaysUsageDescription</key> <string>地理位置權限</string> <key>NSHomeKitUsageDescription</key> <string></string> <key>NSHealthUpdateUsageDescription</key> <string>健康權限</string> <key>NSHealthShareUsageDescription</key> <string>健康權限</string> <key>NSContactsUsageDescription</key> <string>通訊錄權限</string> <key>NSCameraUsageDescription</key> <string>攝像頭權限</string> <key>NSCalendarsUsageDescription</key> <string>日歷權限</string>
下面,正式進入本文要實現的功能的代碼編寫。
1. 使用Xcode的storyboard創(chuàng)建一個button和一個imageView
創(chuàng)建后的效果如下圖1所示。其中,imageView的尺寸影響最終顯示的效果尺寸,請根據實際情況設置。

2. 創(chuàng)建一個UIImage的類別(Category)
創(chuàng)建新文件,選擇“Objective-C File”,如下圖2所示:

在彈出的如圖3所示的對話框中,“File”寫入類別的名稱(本例中是DY),“File Type”選擇Category,“Class”選擇UIImage。然后點擊“Next”按鈕,將新文件保存。

3. 編寫類別中的代碼
UIImage+DY.h文件中
#import <UIKit/UIKit.h> @interface UIImage (DY) + (instancetype)circleOldImage:(UIImage *)originalImage borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor; @end
UIImage+DY.m文件中
#import "UIImage+DY.h"
@implementation UIImage (DY)
+ (instancetype)circleOldImage:(UIImage *)originalImage borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor
{
// 1.加載原圖
UIImage *oldImage = originalImage;
// 2.開啟上下文
CGFloat imageW = oldImage.size.width + 2 * borderWidth;
CGFloat imageH = oldImage.size.height + 2 * borderWidth;
CGSize imageSize = CGSizeMake(imageW, imageH);
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
// 3.取得當前的上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
// 4.畫邊框(大圓)
[borderColor set];
CGFloat bigRadius = imageW * 0.5; // 大圓半徑
CGFloat centerX = bigRadius; // 圓心
CGFloat centerY = bigRadius;
CGContextAddArc(ctx, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
CGContextFillPath(ctx); // 畫圓
// 5.小圓
CGFloat smallRadius = bigRadius - borderWidth;
CGContextAddArc(ctx, centerX, centerY, smallRadius, 0, M_PI * 2, 0);
// 裁剪(后面畫的東西才會受裁剪的影響)
CGContextClip(ctx);
// 6.畫圖
[oldImage drawInRect:CGRectMake(borderWidth, borderWidth, oldImage.size.width, oldImage.size.height)];
// 7.取圖
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
// 8.結束上下文
UIGraphicsEndImageContext();
return newImage;
}
@end
+(instancetype)circleOldImage:(UIImage )originalImage borderWidth:(CGFloat)borderWidth borderColor:(UIColor )borderColor方法的說明:
- 這是一個類方法,最終返回的是一個UIImage的類;
- 方法中originalImage參數指的是從照片庫或者拍照后選中的照片(可能是經過系統裁剪的);
- 方法中borderWidth參數指的是最終顯示的圓形圖像的邊框的寬度,可以可以根據自己的需要設置寬度;
- 方法中的borderColor參數指的是最終顯示的圓形圖像的邊框的顏色,可以可以根據自己的需要設置顏色。
4. 實現裁剪成圓形圖像并顯示
ViewController.h文件
#import <UIKit/UIKit.h> #import "UIImage+DY.h" //加載類別 @interface ViewController : UIViewController<UINavigationControllerDelegate, UIImagePickerControllerDelegate> //一定要添加這兩個Delegate @property (strong, nonatomic) UIImagePickerController *imagePickerController; - (IBAction)btnPressed:(id)sender; @property (strong, nonatomic) IBOutlet UIImageView *ablumImageView; @end
ViewController.m文件
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnPressed:(id)sender {
if([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary]) {
//首先判斷是否支持照片庫,這個方法中的參數要和_imagePickerController.sourceType的值保持一致
//如果支持
_imagePickerController = [[UIImagePickerController alloc]init];
_imagePickerController.view.backgroundColor = [UIColor orangeColor];
_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
_imagePickerController.delegate = self;
_imagePickerController.allowsEditing = YES; //該參數默認是NO,建議設置為YES,否則裁剪成圓形圖片的方法將獲取到的是橢圓形的圖片,與你的預想大相徑庭
[self presentViewController:_imagePickerController animated:YES completion:nil];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
_ablumImageView.image = [UIImage circleOldImage:[info objectForKey:UIImagePickerControllerEditedImage] borderWidth:30.0f borderColor:[UIColor orangeColor]];
//該方法中Info的Key值“UIImagePickerControllerEditedImage”表示的是選擇裁剪后的圖片,如果使用這個Key值,則_imagePickerController.allowsEditing的值需要設置為YES。
//如果_imagePickerController.allowsEditing的值設置的NO,則這個Key的值應該設置為UIImagePickerControllerOriginalImage
/*
info中的Key的值有如下幾個:
NSString *const UIImagePickerControllerMediaType ;指定用戶選擇的媒體類型(文章最后進行擴展)
NSString *const UIImagePickerControllerOriginalImage ;原始圖片
NSString *const UIImagePickerControllerEditedImage ;修改后的圖片
NSString *const UIImagePickerControllerCropRect ;裁剪尺寸
NSString *const UIImagePickerControllerMediaURL ;媒體的URL
NSString *const UIImagePickerControllerReferenceURL ;原件的URL
NSString *const UIImagePickerControllerMediaMetadata;當來數據來源是照相機的時候這個值才有效
*/
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
淺談強大易用支持URL Rewrite的iOS路由庫FFRouter
FRouter 是 iOS 中一個強大且易用的 URL 路由庫,支持 URL Rewrite,基于匹配查找 URL,效率高。非常具有實用價值,需要的朋友可以參考下2018-10-10
iOS應用開發(fā)中UITableView的分割線的一些設置技巧
這篇文章主要介紹了iOS應用開發(fā)中UITableView分割線的一些設置技巧,包括消除分割線的方法,示例代碼為傳統的Objective-C語言,需要的朋友可以參考下2016-03-03
iOS動畫解析之圓球加載動畫XLBallLoading的實現
加載動畫對大家來說都不陌生,我們在平時都會遇見,開發(fā)中也必不可少,所以下面這篇文章主要給大家介紹了關于iOS動畫解析之圓球加載動畫XLBallLoading實現的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。2017-11-11
cmake ios終端下執(zhí)行提示錯誤 iOS version not found, tested: [5.0;5.1;6
這篇文章主要介紹了cmake ios終端下執(zhí)行提示錯誤 iOS version not found, tested: [5.0;5.1;6.0;6.1;7.0;8.3]的解決方案的相關資料,需要的朋友可以參考下2016-10-10
ios實現底部PopupWindow的示例代碼(底部彈出菜單)
這篇文章主要介紹了ios實現底部PopupWindow的示例代碼(底部彈出菜單),小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
IOS中(Xcode) DEBUG模式(RELEASE模式)控制NSLog輸出,NSLog輸出方式
這篇文章主要介紹了IOS中(Xcode) DEBUG模式(RELEASE模式)控制NSLog輸出,NSLog輸出方式的相關資料,需要的朋友可以參考下2016-11-11

