iOS 修改頭像,幾行程式碼實現從相簿選擇照片
我的GitHub:點選開啟連結
SelectPhotoManager.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
typedefenum {
PhotoCamera = 0,
PhotoAlbum,
}SelectPhotoType;
@protocol selectPhotoDelegate <NSObject>
//照片選取成功
- (void)selectPhotoManagerDidFinishImage:(UIImage *)image;
//照片選取失敗
- (void)selectPhotoManagerDidError:(NSError *)error;
@end
@interface SelectPhotoManager : NSObject<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
//代理物件
@property(nonatomic, weak)__weakid<selectPhotoDelegate>delegate;
//是否開啟照片編輯功能
@property
//跳轉的控制器可選引數
@property(nonatomic, weak)__weakUIViewController *superVC;
//照片選取成功回撥
@property(nonatomic, strong)void (^successHandle)(SelectPhotoManager *manager, UIImage *image);
//照片選取失敗回撥
@property(nonatomic, strong)void (^errorHandle)(NSString *error);
//開始選取照片
- (void)startSelectPhotoWithImageName:(NSString *)imageName;
- (void)startSelectPhotoWithType:(SelectPhotoType )type andImageName:(NSString *)imageName;
@end
SelectPhotoManager.m 檔案
#import "SelectPhotoManager.h"
@implementation SelectPhotoManager {
//圖片名
NSString *_imageName;
}
- (instancetype)init {
self = [superinit];
if (self) {
_canEditPhoto = YES;
}
returnself;
}
//開始選擇照片
- (void)startSelectPhotoWithImageName:(NSString *)imageName{
_imageName = imageName;
UIAlertController *alertController = [UIAlertControlleralertControllerWithTitle:@"修改我的頭像"message:nilpreferredStyle: UIAlertControllerStyleActionSheet];
UIAlertAction *cancelAction = [UIAlertActionactionWithTitle:@"取消"style:UIAlertActionStyleCancelhandler:nil];
[alertController addAction: [UIAlertActionactionWithTitle: @"拍照"style: UIAlertActionStyleDefaulthandler:^(UIAlertAction *action) {
[selfselectPhotoWithType:0];
}]];
[alertController addAction: [UIAlertActionactionWithTitle: @"從相簿獲取"style: UIAlertActionStyleDefaulthandler:^(UIAlertAction *action) {
[selfselectPhotoWithType:1];
}]];
[alertController addAction:cancelAction];
[[selfgetCurrentVC] presentViewController:alertController animated:YEScompletion:nil];
}
//根據型別選取照片
- (void)startSelectPhotoWithType:(SelectPhotoType)type andImageName:(NSString *)imageName {
_imageName = imageName;
UIImagePickerController *ipVC = [[UIImagePickerControlleralloc] init];
//設定跳轉方式
ipVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
if (_canEditPhoto) {
//設定是否可對圖片進行編輯
ipVC.allowsEditing = YES;
}
ipVC.delegate = self;
if (type == PhotoCamera) {
NSLog(@"相機");
BOOL isCamera = [UIImagePickerControllerisCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
if (!isCamera) {
NSLog(@"沒有攝像頭");
if (_errorHandle) {
_errorHandle(@"沒有攝像頭");
}
UIAlertController *alertController = [UIAlertControlleralertControllerWithTitle:@"提示"message:@"您的裝置不支援拍照"preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction: [UIAlertActionactionWithTitle: @"確定"style: UIAlertActionStyleDefaulthandler:^(UIAlertAction *action) {
}]];
[[selfgetCurrentVC] presentViewController:alertController animated:YEScompletion:nil];
return ;
}else{
ipVC.sourceType = UIImagePickerControllerSourceTypeCamera;
}
}else{
NSLog(@"相簿");
ipVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
[[selfgetCurrentVC] presentViewController:ipVC animated:YEScompletion:nil];
}
//獲取當前螢幕顯示的viewcontroller
- (UIViewController *)getCurrentVC {
if (_superVC) {
return_superVC;
}
UIViewController *result = nil;
UIWindow * window = [[UIApplicationsharedApplication] keyWindow];
if (window.windowLevel != UIWindowLevelNormal)
{
NSArray *windows = [[UIApplicationsharedApplication] windows];
for(UIWindow * tmpWin in windows)
{
if (tmpWin.windowLevel == UIWindowLevelNormal)
{
window = tmpWin;
break;
}
}
}
UIView *frontView = [[window subviews] objectAtIndex:0];
id nextResponder = [frontView nextResponder];
if ([nextResponder isKindOfClass:[UIViewControllerclass]]) {
result = nextResponder;
}else{
result = window.rootViewController;
}
return result;
}
#pragma mark 方法
-(void)selectPhotoWithType:(int)type {
if (type == 2) {
NSLog(@"取消");
}else{
UIImagePickerController *ipVC = [[UIImagePickerControlleralloc] init];
//設定跳轉方式
ipVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
if (_canEditPhoto) {
//設定是否可對圖片進行編輯
ipVC.allowsEditing = YES;
}
ipVC.delegate = self;
if (type == 0) {
NSLog(@"相機");
BOOL isCamera = [UIImagePickerControllerisCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
if (!isCamera) {
NSLog(@"沒有攝像頭");
if (_errorHandle) {
_errorHandle(@"沒有攝像頭");
}
UIAlertController *alertController = [UIAlertControlleralertControllerWithTitle:@"提示"message:@"您的裝置不支援拍照"preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction: [UIAlertActionactionWithTitle: @"確定"style: UIAlertActionStyleDefaulthandler:^(UIAlertAction *action) {
}]];
[[selfgetCurrentVC] presentViewController:alertController animated:YEScompletion:nil];
return ;
}else{
ipVC.sourceType = UIImagePickerControllerSourceTypeCamera;
}
}else{
NSLog(@"相簿");
ipVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
[[selfgetCurrentVC] presentViewController:ipVC animated:YEScompletion:nil];
}
}
#pragma mark -----------------imagePickerController協議方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSLog(@"info = %@",info);
UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
if (image == nil) {
image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
}
//圖片旋轉
if (image.imageOrientation != UIImageOrientationUp) {
//圖片旋轉
image = [selffixOrientation:image];
}
if (_imageName==nil || _imageName.length == 0) {
//獲取當前時間,生成圖片路徑
NSDate *date = [NSDatedate];
NSDateFormatter *formatter = [[NSDateFormatteralloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
NSString *dateStr = [formatter stringFromDate:date];
_imageName = [NSStringstringWithFormat:@"photo_%@.png",dateStr];
}
[[selfgetCurrentVC] dismissViewControllerAnimated:YEScompletion:nil];
if (_delegate && [_delegaterespondsToSelector:@selector(selectPhotoManagerDidFinishImage:)]) {
[_delegateselectPhotoManagerDidFinishImage:image];
}
if (_successHandle) {
_successHandle(self,image);
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[[selfgetCurrentVC] dismissViewControllerAnimated:YEScompletion:nil];
if (_delegate && [_delegaterespondsToSelector:@selector(selectPhotoManagerDidError:)]) {
[_delegateselectPhotoManagerDidError:nil];
}
if (_errorHandle) {
_errorHandle(@"撤銷");
}
}
#pragma mark 圖片處理方法
//圖片旋轉處理
- (UIImage *)fixOrientation:(UIImage *)aImage {
CGAffineTransform transform = CGAffineTransformIdentity;
switch (aImage.imageOrientation) {
caseUIImageOrientationDown:
caseUIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
caseUIImageOrientationLeft:
caseUIImageOrientationLeftMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
transform = CGAffineTransformRotate(transform, M_PI_2);
break;
caseUIImageOrientationRight:
caseUIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
transform = CGAffineTransformRotate(transform, -M_PI_2);
break;
default:
break;
}
switch (aImage.imageOrientation) {
caseUIImageOrientationUpMirrored:
caseUIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
caseUIImageOrientationLeftMirrored:
caseUIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
default:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
CGImageGetBitsPerComponent(aImage.CGImage), 0,
CGImageGetColorSpace(aImage.CGImage),
CGImageGetBitmapInfo(aImage.CGImage));
CGContextConcatCTM(ctx, transform);
switch (aImage.imageOrientation) {
caseUIImageOrientationLeft:
caseUIImageOrientationLeftMirrored:
caseUIImageOrientationRight:
caseUIImageOrientationRightMirrored:
// Grr...
CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
break;
default:
CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
break;
}
// And now we just create a new UIImage from the drawing context
CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
UIImage *img = [UIImageimageWithCGImage:cgimg];
CGContextRelease(ctx);
CGImageRelease(cgimg);
return img;
}
@end
在controller裡實現下方法即可
//頭像點選事件
-(void)tapClick:(UITapGestureRecognizer *)recognizer{
if (!_photoManager) {
_photoManager =[[SelectPhotoManageralloc]init];
}
[_photoManagerstartSelectPhotoWithImageName:@"選擇頭像"];
__weaktypeof(self)mySelf=self;
//選取照片成功
_photoManager.successHandle=^(SelectPhotoManager *manager,UIImage *image){
mySelf.headerImage.image = image;
//儲存到本地
NSData *data = UIImagePNGRepresentation(image);
[[NSUserDefaultsstandardUserDefaults] setObject:data forKey:@"headerImage"];
};
}
我的GitHub:點選開啟連結