iOS 修改头像,几行代码实现从相册选择照片

来源:互联网 发布:桝太一 知乎 编辑:程序博客网 时间:2024/06/02 18:10

我的GitHub:点击打开链接




SelectPhotoManager.h

#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>

typedef enum {

    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(nonatomic,assign)BOOL canEditPhoto;

//跳转的控制器可选参数

@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:alertControlleranimated: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:alertControlleranimated:YEScompletion:nil];

            return ;

        }else{

            ipVC.sourceType =UIImagePickerControllerSourceTypeCamera;

        }

    }else{

        NSLog(@"相册");

        ipVC.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;

    }

    

    [[selfgetCurrentVC]presentViewController:ipVCanimated: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 * tmpWinin windows)

        {

            if (tmpWin.windowLevel ==UIWindowLevelNormal)

            {

                window = tmpWin;

                break;

            }

        }

    }

    

    UIView *frontView = [[windowsubviews] objectAtIndex:0];

    id nextResponder = [frontViewnextResponder];

    

    if ([nextResponderisKindOfClass:[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:alertControlleranimated:YEScompletion:nil];

                return ;

            }else{

                ipVC.sourceType =UIImagePickerControllerSourceTypeCamera;

            }

        }else{

            NSLog(@"相册");

            ipVC.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;

            

        }

        [[selfgetCurrentVC]presentViewController:ipVCanimated:YEScompletion:nil];

    }

}


#pragma mark -----------------imagePickerController协议方法

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{

    NSLog(@"info = %@",info);

    UIImage *image = [infoobjectForKey:@"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 = [formatterstringFromDate: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:点击打开链接