iOS - 拍照功能、选择照片功能和选择视频,长按删除、预览等

一.使用 UIPickerViewController 自定义相机和相册功能

备用:

   1.  在info.plist里面添加Localized resources can be mixed设置为YES(表示是否允许应用程序获取框架库内语言) 

    2.提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - 秀贝] 打开访问开关" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //确定按钮点击事件处理
        }]];
    [self presentViewController:alert animated:YES completion:nil];

** 第一.调用相机方法 (系统版)**

    - (void)takePhoto{
      if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;/** 设置拍照后的图片可被编辑 */
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            //录制视频时长,默认10s
            picker.videoMaximumDuration = 15;
            //相机类型(拍照、录像...)字符串需要做相应的类型转换
            picker.mediaTypes = @[(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage];
            picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
            //设置摄像头模式(拍照,录制视频)为录像模式
            picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
            
            [self presentViewController:picker animated:YES completion:^{
                [UIApplication sharedApplication].statusBarHidden = YES;;
            }];
        }else{
            NSLog(@"模拟机无法打开照相机,请在真机使用");
        }
    }

** 第二.调用相机方法 (自定义版)如图 **

55D48AA898FC2FB26F99D0E9DBFF1055.jpg
    1.属性相关
        @property (nonatomic , copy) NSString *openCamera;
        @property (nonatomic , strong) MSUPickerControlView *controlView;//自定义的类文件实现自定义视图

   2.自定义类文件,继承于UIView

        1) MSUPickerControlView.h 中的代码

            #import <UIKit/UIKit.h>

            @interface MSUPickerControlView : UIView
            
            @property (nonatomic , strong) UIButton *closeBtn;
            
            @property (nonatomic , strong) UIButton *pickBtn;
            @property (nonatomic , copy) void(^pickBtnTouchDownBlock)(UIButton *btn);
            @property (nonatomic , copy) void(^pickBtnClickBlock)(UIButton *btn);
            
            
            @property (nonatomic , strong) UIProgressView *processView;
            
            @property (nonatomic , strong) UIButton *flashBtn;
            @property (nonatomic , copy) void(^flashBtnClickBlock)(UIButton *btn);
            
            @property (nonatomic , strong) UIButton *positionBtn;
            @property (nonatomic , copy) void(^positionBtnClickBlock)(UIButton *btn);
            
            @end

        2) MSUPickerControlView.m 中的代码

            #import "MSUPickerControlView.h"
            #import "MSUPathTools.h"
            
            #define HEXCOLOR(rgbValue)      [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
            //masonry
            #define MAS_SHORTHAND
            #define MAS_SHORTHAND_GLOBALS
            #import "Masonry.h"
            
            #define SelfWidth [UIScreen mainScreen].bounds.size.width
            #define SelfHeight [UIScreen mainScreen].bounds.size.height
            
            
            @implementation MSUPickerControlView
            
            - (instancetype)initWithFrame:(CGRect)frame
            {
                if (self = [super initWithFrame:frame]) {
                    
                    [self createView];
                    
                }
                return self;
            }
            
            
            - (void)createView{
                self.closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                _closeBtn.adjustsImageWhenHighlighted = NO;
                _closeBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
                [_closeBtn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-close"] forState:UIControlStateNormal];
                _closeBtn.layer.cornerRadius = 10;
                _closeBtn.layer.shouldRasterize = YES;
                _closeBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;
                [self addSubview:_closeBtn];
                [_closeBtn makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(self.top).offset(24);
                    make.left.equalTo(self.left).offset(14);
                    make.width.equalTo(20);
                    make.height.equalTo(20);
                }];
                
                UIView *bgView = [[UIView alloc] init];
                bgView.backgroundColor = HEXCOLOR(0xffffff);
                [self addSubview:bgView];
                [bgView makeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(self.bottom).offset(0);
                    make.left.equalTo(self.left).offset(0);
                    make.width.equalTo(SelfWidth);
                    make.height.equalTo(150);
                }];
                
                self.pickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                _pickBtn.adjustsImageWhenHighlighted = NO;
                _pickBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
            //    [_pickBtn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-close"] forState:UIControlStateNormal];
                _pickBtn.backgroundColor = HEXCOLOR(0xf7d721);
                [_pickBtn setTitle:@"按住拍" forState:UIControlStateNormal];
                [_pickBtn setTitleColor:HEXCOLOR(0xffffff) forState:UIControlStateNormal];
                _pickBtn.titleLabel.font = [UIFont systemFontOfSize:14];
                _pickBtn.layer.shadowColor = HEXCOLOR(0xf7d721).CGColor;
                _pickBtn.layer.shadowOpacity = 0.6;
                _pickBtn.layer.shadowOffset = CGSizeZero;
                _pickBtn.layer.shadowRadius = 5;
                _pickBtn.layer.cornerRadius = 39;
                _pickBtn.layer.shouldRasterize = YES;
                _pickBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;
                [self addSubview:_pickBtn];
                [_pickBtn makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(bgView.top).offset(36);
                    make.left.equalTo(self.left).offset(SelfWidth*0.5-49);
                    make.width.equalTo(78);
                    make.height.equalTo(78);
                }];
                [_pickBtn addTarget:self action:@selector(pickBtnClick:) forControlEvents:UIControlEventTouchDown];
                [_pickBtn addTarget:self action:@selector(pickBtnCancelClick:) forControlEvents:UIControlEventTouchUpInside];
            
                self.processView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
                [self addSubview:_processView];
                [_processView makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(bgView.top).offset(-5);
                    make.left.equalTo(bgView.left).offset(0);
                    make.width.equalTo(SelfWidth);
                    make.height.equalTo(5);
                }];
                _processView.trackTintColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5];
                _processView.progressTintColor = HEXCOLOR(0xf7d721);
                //设置进度
            //    _processView.progress = 0.2;
                
                self.positionBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                _positionBtn.adjustsImageWhenHighlighted = NO;
                _positionBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
                [_positionBtn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-camera-exchange"] forState:UIControlStateNormal];
                [self addSubview:_positionBtn];
                [_positionBtn makeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(_processView.top).offset(-23);
                    make.right.equalTo(self.right).offset(-39);
                    make.width.equalTo(30);
                    make.height.equalTo(23);
                }];
                [_positionBtn addTarget:self action:@selector(positionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            
                
                self.flashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                _flashBtn.adjustsImageWhenHighlighted = NO;
                _flashBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
                [_flashBtn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-light-auto"] forState:UIControlStateNormal];
                [self addSubview:_flashBtn];
                [_flashBtn makeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(_processView.top).offset(-23);
                    make.right.equalTo(_positionBtn.left).offset(-35);
                    make.width.equalTo(21.5);
                    make.height.equalTo(24.5);
                }];
                [_flashBtn addTarget:self action:@selector(flashBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            }
            
            
            #pragma mark - 点击事件
            - (void)positionBtnClick:(UIButton *)sender{
                if (self.positionBtnClickBlock) {
                    self.positionBtnClickBlock(sender);
                }
            }
            
            - (void)flashBtnClick:(UIButton *)sender{
                if (self.flashBtnClickBlock) {
                    self.flashBtnClickBlock(sender);
                }
            }
            
            - (void)pickBtnClick:(UIButton *)sender{
                if (self.pickBtnTouchDownBlock) {
                    self.pickBtnTouchDownBlock(sender);
                }
            }
            
            - (void)pickBtnCancelClick:(UIButton *)sender{
                if (self.pickBtnClickBlock) {
                    self.pickBtnClickBlock(sender);
                }
            }


   3. /* 拍照和录视频 */
    - (void)takePictureAndCamera{
        //  MSUPermissionTool是封装相关权限的类,可根据自己情况写自己的
        [MSUPermissionTool getCamerasPermission:^(NSInteger authStatus) {
            if (authStatus == 1) {
                self.openCamera = @"开启";
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
                    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    picker.delegate = self;
    //                picker.allowsEditing = YES;/** 设置拍照后的图片可被编辑 */
                    
                    //录制视频时长,默认10s
                    picker.videoMaximumDuration = 10;
                    //相机类型(拍照、录像...)字符串需要做相应的类型转换
    //                picker.mediaTypes = @[(NSString *)kUTTypeImage,(NSString *)kUTTypeMovie];
                    picker.mediaTypes = @[(NSString *)kUTTypeMovie];
                    picker.videoQuality = UIImagePickerControllerQualityTypeIFrame960x540;
                    //设置摄像头模式(拍照,录制视频)为录像模式
                    picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;
    
                    CGSize screenBounds = [UIScreen mainScreen].bounds.size;
                    CGFloat cameraAspectRatio = 4.0f/3.0f;
                    CGFloat camViewHeight = screenBounds.width * cameraAspectRatio;
                    CGFloat scale = screenBounds.height / camViewHeight;
                    picker.cameraViewTransform = CGAffineTransformMakeTranslation(0, (screenBounds.height - camViewHeight) / 2.0);
                    picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, scale, scale);
    //                CGAffineTransform transform = CGAffineTransformMakeTranslation(0.0f, -200.0f);
    //                transform = CGAffineTransformScale(transform, 1.0f, 0.5f);
    //                picker.cameraViewTransform = transform;
                    
                    // 自定义录像视频页面
                    picker.showsCameraControls = NO;
                    self.controlView = [[MSUPickerControlView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
                    _controlView.backgroundColor = [UIColor clearColor];
                    picker.cameraOverlayView = _controlView; // 自定义控件view
                    // 关闭按钮
                    [_controlView.closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                    // 前后摄像头
                    _controlView.positionBtnClickBlock = ^(UIButton *btn) {
                        btn.selected = !btn.selected;
                        picker.cameraDevice = btn.selected?UIImagePickerControllerCameraDeviceFront:UIImagePickerControllerCameraDeviceRear;
                    };
                    // 闪光灯状态
                    static NSInteger x;
                    _controlView.flashBtnClickBlock = ^(UIButton *btn) {
                        x += 1;
                        if (x == 3) {
                            x = 0;
                        }
                        switch (x) {
                            case 0:
                            {
                                [btn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-light-auto"] forState:UIControlStateNormal];
                                picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
                            }
                                break;
                            case 1:
                            {
                                [btn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-light-on"] forState:UIControlStateNormal];
                                picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOn;
                            }
                                break;
                            case 2:
                            {
                                [btn setImage:[MSUPathTools showImageWithContentOfFileByName:@"record-light-close"] forState:UIControlStateNormal];
                                picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOff;
                            }
                                break;
                                
                            default:
                                break;
                        }
    
                    };
                    
                    // 拍摄按钮
                    __weak typeof(self) weakSelf = self;
                    _controlView.pickBtnTouchDownBlock = ^(UIButton *btn) {
                        // 判断与设备方向
                                            
                        weakSelf.motionManager = [[CMMotionManager alloc] init];
                        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
                        if (weakSelf.motionManager.accelerometerAvailable) {
                            weakSelf.motionManager.accelerometerUpdateInterval = 1;
                            [weakSelf.motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
                                if (error) {
                                    [weakSelf.motionManager stopAccelerometerUpdates];
                                    NSLog(@"error");
                                } else {
    //                                NSLog(@"x 加速度--> %f\n y 加速度--> %f\n z 加速度--> %f\n", accelerometerData.acceleration.x, accelerometerData.acceleration.y, accelerometerData.acceleration.z);
                                  // 根据 accelerometerData.acceleration.x/y/z来区分手机横竖屏状态。
                                    if (accelerometerData.acceleration.x > accelerometerData.acceleration.y && accelerometerData.acceleration.y < 0) {
                                        NSLog(@"竖屏");
                                        weakSelf.statusStr = @"竖屏";
                                    } else if (accelerometerData.acceleration.x < 0 && accelerometerData.acceleration.y > 0){
                                        NSLog(@"横屏");
                                        weakSelf.statusStr = @"横屏";
    
                                    } else if (accelerometerData.acceleration.x > 0 && accelerometerData.acceleration.y > 0){
                                        NSLog(@"横屏");
                                        weakSelf.statusStr = @"横屏";
    
                                    }
                                    
                                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                        [weakSelf.motionManager stopDeviceMotionUpdates];
                                        [weakSelf.motionManager stopAccelerometerUpdates];
                                    });
                                }
                            }];
                            } else {
                                NSLog(@"This device has no accelerometer");
                            }
            
                        // 开始录像
                        [picker startVideoCapture];
    
                        weakSelf.time = 0;
                        weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timeChange:) userInfo:nil repeats:YES];
                        [[NSRunLoop currentRunLoop]addTimer:weakSelf.timer forMode:NSRunLoopCommonModes];
                    };
                    
                    _controlView.pickBtnClickBlock = ^(UIButton *btn) {
                        if (weakSelf.timer) {
                            [MSUHUD showStatusWithString:@"正在处理"];
                            [picker stopVideoCapture];
                            [weakSelf.timer invalidate];
                            weakSelf.timer = nil;
                            [UIView animateWithDuration:1 animations:^{
                                weakSelf.controlView.processView.progress = 0;
                            }];
                        } else{
                            
                        }
                        
                    };
                    
                    [self.navigationController presentViewController:picker animated:YES completion:^{
                        [UIApplication sharedApplication].statusBarHidden = YES;;
                    }];
                    
                }else{
                    NSLog(@"模拟机无法打开照相机,请在真机使用");
                }
            }else{
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - 秀贝] 打开访问开关" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    //确定按钮点击事件处理
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }
    
    - (void)timeChange:(NSTimer *)timer{
        _time++;
        CGFloat value = _time;
    //    NSLog(@"-----%f,%ld",value/10,_time);
        [UIView animateWithDuration:1 animations:^{
            _controlView.processView.progress = value/10;
        }];
        if (value >= 10) {
            [self.timer invalidate];
            self.timer = nil;
        }
    }

第三.选择照片功能

        -(void)LocalPhoto
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.delegate = self;
            //设置选择后的图片可被编辑
            picker.allowsEditing = YES;
            [self presentViewController:picker animated:YES completion:nil];
        }

第四.选择视频功能

    - (void)pickedMedia{
        // 1、 获取摄像设备
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if (device) {
            [MSUPermissionTool getPhotosPermission:^(NSInteger authStatus) {
                if (authStatus == 1) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
                        // 选择视频方式
                        imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
                        imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                        imagePicker.delegate = self;
                        //                    imagePicker.allowsEditing = YES;
                        [self presentViewController:imagePicker animated:YES completion:^{
                            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
                        }];
                    });
                    
                }else{
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 照片 - 秀贝] 打开访问开关" preferredStyle:UIAlertControllerStyleAlert];
                    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        //确定按钮点击事件处理
                    }]];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }];
        }
    
    }

** 第四、代理方法**

 #pragma mark UIImagePickerControllerDelegate
//适用获取所有媒体资源,只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    NSLog(@"===========%@",info);
    
    //判断资源类型
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
        //如果是图片
        UIImage *pickedImage = nil;
        if ([picker allowsEditing]) {
            pickedImage = info[UIImagePickerControllerEditedImage];
        }else{
            pickedImage = info[UIImagePickerControllerOriginalImage];
        }
        
        NSLog(@"图片是%@",pickedImage);
        //        self.imageView.image = info[UIImagePickerControllerEditedImage];
        //        //压缩图片
        //        NSData *fileData = UIImageJPEGRepresentation(self.imageView.image, 1.0);
        //        //保存图片至相册
        UIImageWriteToSavedPhotosAlbum(pickedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        //        //上传图片
        //        [self uploadImageWithData:fileData];
        
    }else{
        [MSUHUD dismiss];

        //如果是视频
        NSURL *url = info[UIImagePickerControllerMediaURL];
        CGSize videoSize = [MSUCameraPhotoVc getVideoSizeWithURL:url];
        NSLog(@"视频链接是%@",url);
        NSLog(@"宽 :%f , 高 : %f",videoSize.width,videoSize.height);
        
        CGFloat videoLenth = [MSUCameraPhotoVc getVideoDuration:url];
        NSLog(@"视频时长 %f",videoLenth);
        
        UISaveVideoAtPathToSavedPhotosAlbum([url path], self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        
//        self.hidesBottomBarWhenPushed = YES;
        //        self.selectedViewController = [self.viewControllers objectAtIndex:2];
        if (videoLenth < 3) {
            [MSUHUD showFileWithString:@"最短拍摄时间不能低于三秒,请重新拍摄"];
        } else{
            MSUFilterController *filter = [[MSUFilterController alloc] init];
            filter.videoUrl = url;
            filter.statusStr = self.statusStr;
            [picker pushViewController:filter animated:YES];
            self.hidesBottomBarWhenPushed = NO;
        }
        
        
        
        //        //播放视频
        //        _moviePlayer.contentURL = url;
        //        [_moviePlayer play];
        //        //保存视频至相册(异步线程)
        //        NSString *urlStr = [url path];
        //
        //        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
        //
        //                UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        //            }
        //        });
        //        NSData *videoData = [NSData dataWithContentsOfURL:url];
        //        //视频上传
        //        [self uploadVideoWithData:videoData];
    }
//    [self dismissViewControllerAnimated:YES completion:nil];
}

/** 取消按钮回调 */
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/* 图片保存完毕的回调 */
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
    if (error) {
        NSLog(@"保存照片过程中发生错误,错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"照片保存成功.");
    }
}

/* 视频保存完毕的回调 */
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
    if (error) {
        NSLog(@"保存视频过程中发生错误,错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"视频保存成功.");
    }
}

第五、下挂商品图标,预览、删除等

1. 导入第三方 MSImagePickerController,导入相关属性
    
    /// 添加图片
    @property (nonatomic , strong) UIButton *addBtn;
    @property (nonatomic , strong) UIImage *pickIma;
    @property (retain, nonatomic) NSMutableArray* array;
    @property (nonatomic , strong) UIView *picView;

2.点击按钮,打开照片

    - (void)addBtnClick:(UIButton *)sender{
        MSImagePickerController* picker = [[MSImagePickerController alloc] init];
        picker.msDelegate = self;
        picker.maxImageCount = 4;
        picker.doneButtonTitle = @"确定";
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:true completion:^{
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
        }];
    }

3.实现代理方法 MSImagePickerController Delegate

    #pragma mark - MSImagePickerController Delegate method
    - (void)imagePickerControllerDidCancel:(MSImagePickerController *)picker; {
        [picker dismissViewControllerAnimated:true completion:^{
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        }];
        NSLog(@"do cancel");
    }
    
    - (void)imagePickerControllerDidFinish:(MSImagePickerController *)picker {
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
        self.array = [picker.images mutableCopy];
        
        self.addBtn.hidden = YES;
        
        self.picView = [[UIView alloc] init];
        // 图片放置位置  frame自设
        _picView.frame = CGRectMake(0,270+60 , WIDTH, 80);
        _picView.backgroundColor = HEXCOLOR(0xffffff);
        [self.view addSubview:_picView];
        
        for (UIImage* img in self.array) {
            NSData* data = [MSUStringTools compressOriginalImage:img withScale:1];
            if (data != nil) {
                
                for (NSInteger i = 0; i < self.array.count; i++) {
                    UIButton *privateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                    // 根据pickView 自设frame
                    privateBtn.frame = CGRectMake(14 + 90*i, 0, 80, 80);
                    [privateBtn setImage:self.array[i] forState:UIControlStateNormal];
                    privateBtn.adjustsImageWhenHighlighted = NO;
                    privateBtn.tag = 1650+i;
                    [_picView addSubview:privateBtn];
                    [privateBtn addTarget:self action:@selector(privateBtnTouchInClick:) forControlEvents:UIControlEventTouchDown];
                    
                    UILongPressGestureRecognizer *tap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressClick:)];
                    tap.delegate = self;
                     tap.minimumPressDuration = 1.0;
                    tap.numberOfTouchesRequired = 1;
                    [privateBtn addGestureRecognizer:tap];
    
                }
            }
        }
        
        [picker dismissViewControllerAnimated:true completion:^{
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    //        QLPreviewController* ql = [[QLPreviewController alloc] init];
    //        ql.dataSource = self;
    //        [self presentViewController:ql
    //                           animated:true
    //                         completion:nil];
        }];
    }
    
    - (void)imagePickerControllerOverMaxCount:(MSImagePickerController *)picker; // 选择的图片超过上限的时候调用
    {
        NSString* message = [NSString stringWithFormat:@"你最多只能选择%ld张图片。", picker.maxImageCount];
        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil, nil];
        
        [alert show];
    }
    
    4.实现预览功能 

        #pragma mark - QLPreviewController Delegate method
        /*!
         * @abstract Returns the number of items that the preview controller should preview.
         * @param controller The Preview Controller.
         * @result The number of items.
         */
        - (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller; {
            return self.array.count;
        }
        
        /*!
         * @abstract Returns the item that the preview controller should preview.
         * @param index The index of the item to preview.
         * @result An item conforming to the QLPreviewItem protocol.
         */
        - (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index; {
            NSString* path = [NSString stringWithFormat:@"%@/%ld.png", [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject], (long)index];
            NSURL* url = [[NSURL alloc] initFileURLWithPath:path];
            
            return (id <QLPreviewItem>)url;
        }

    5.实现长按删除,再添加等

        /* 删除图片按钮事件 */
        - (void)chachaBtnClick:(UIButton *)sender{
            NSInteger a = sender.tag-1633;
            [self.array removeObjectAtIndex:a];
            
        //    UIButton *btn = [self.picView viewWithTag:a+1650];
        //    [sender removeFromSuperview];
        //    [btn removeFromSuperview];
        //    [self.picView layoutIfNeeded];
            [self.picView removeFromSuperview];
            self.picView = [[UIView alloc] init];
            _picView.frame = CGRectMake(0,270+60 , WIDTH, 80);
            _picView.backgroundColor = HEXCOLOR(0xffffff);
            [self.view addSubview:_picView];
            
            for (NSInteger i = 0; i < self.array.count; i++) {
                UIButton *privateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                privateBtn.frame = CGRectMake(14 + 90*i, 0, 80, 80);
                [privateBtn setImage:self.array[i] forState:UIControlStateNormal];
                privateBtn.adjustsImageWhenHighlighted = NO;
                [_picView addSubview:privateBtn];
                [privateBtn addTarget:self action:@selector(privateBtnTouchInClick:) forControlEvents:UIControlEventTouchDown];
                
                UILongPressGestureRecognizer *tap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressClick:)];
                tap.delegate = self;
                tap.minimumPressDuration = 1.0;
                tap.numberOfTouchesRequired = 1;
                [privateBtn addGestureRecognizer:tap];
            }
        
            if (self.array.count == 0) {
                [self.picView removeFromSuperview];
                self.addBtn.hidden = NO;
            }
            
        }
        
        - (void)longPressClick:(UILongPressGestureRecognizer *)sender{
            if(sender.state == UIGestureRecognizerStateBegan)
            {
                for (NSInteger i = 0; i < self.array.count; i++) {
                    UIButton *privateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                    privateBtn.frame = CGRectMake(14 + 60 + 90*i, 0, 20, 20);
                    privateBtn.layer.cornerRadius = 10;
                    privateBtn.clipsToBounds = YES;
                    privateBtn.layer.shouldRasterize = YES;
                    privateBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;
                    privateBtn.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
                    [privateBtn setImage:[MSUPathTools showImageWithContentOfFileByName:@"WechatIMG448"] forState:UIControlStateNormal];
                    privateBtn.adjustsImageWhenHighlighted = NO;
                    privateBtn.tag = 1633+i;
                    [self.picView addSubview:privateBtn];
                    [privateBtn addTarget:self action:@selector(chachaBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                }
            }
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,252评论 6 516
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,886评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,814评论 0 361
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,869评论 1 299
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,888评论 6 398
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,475评论 1 312
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 41,010评论 3 422
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,924评论 0 277
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,469评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,552评论 3 342
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,680评论 1 353
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,362评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,037评论 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,519评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,621评论 1 274
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,099评论 3 378
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,691评论 2 361

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,310评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,123评论 4 61
  • #2017.2.23早餐#今日早餐:五彩丁、水煮蛋、全麦馒头、二米粥、农夫甜橙。昨晚发了面粉,一大早起来蒸了全麦馒...
    雪宝吃饭饭阅读 207评论 0 0
  • 好久不出门,你开始思量远方。 有个声响,由弱渐强。 终于,躁动的心,穿过你的胸膛,穿过我的叹息,穿过喧嚣的城市,到...
    bladehliu阅读 196评论 0 2
  • 睡前,给你灌碗鸡汤。 人生最大的成功就是能让自己,在自己有限的生命当中,能享受到比痛苦更多的快乐。 当然这是一碗鸡...
    旦真陈里阅读 154评论 0 0