iOS開發:相冊或相機調用

一、相冊、相機、攝像的調用

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>                              //添加靜態庫頭文件
@interface ViewController ()<UIImagePickerControllerDelegate>      //遵守協議並實現協議方法
@property (nonatomic, strong) UIImagePickerController * picker;    //控制器
@property (nonatomic, strong) UIImageView             * imageView; //顯示相冊或拍照的圖片
@property (nonatomic, strong) AVPlayer                * player;    //用於顯示動畫
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getPhotoBtn];
    [self getCamera];
    [self showPhoto];
}

-(void)getPhotoBtn{
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(20, 70, 200, 100);
    btn.backgroundColor = [UIColor lightGrayColor];
    [btn setTitle:@"相冊" forState:UIControlStateNormal];
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(fromPhotoLibrary) forControlEvents:UIControlEventTouchUpInside];
}

-(void)getCamera{
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(20, 200, 200, 100);
    btn.backgroundColor = [UIColor lightGrayColor];
    [btn setTitle:@"相機" forState:UIControlStateNormal];
    [self.view addSubview:btn];
    [btn addTarget:self action:@selector(fromCamera) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)showPhoto{
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 320, 200, 200)];
    imageView.backgroundColor = [UIColor redColor];
    _imageView = imageView;
    [self.view addSubview:imageView];
    
}


/*
 sourceType:用來確定用戶界面顯示的樣式
 
 @property(nonatomic) UIImagePickerControllerSourceType sourceType
 enum {
 UIImagePickerControllerSourceTypePhotoLibrary,//顯示圖庫
 UIImagePickerControllerSourceTypeCamera,//顯示相機
 UIImagePickerControllerSourceTypeSavedPhotosAlbum//顯示moment圖片
 };
 typedef NSUInteger UIImagePickerControllerSourceType;
 */


// 調起手機相冊
- (void)fromPhotoLibrary
{
    _picker = [[UIImagePickerController alloc] init];
    _picker.delegate = (id)self;
    
    //1、默認選項是:UIImagePickerControllerSourceTypePhotoLibrary
    _picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    //2、針對_picker.sourceType返回所有可用的mediaTypes.
    _picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    
    //3、是否允許對獲得的圖片進行編輯,default value is NO.
    _picker.allowsEditing   = YES;
    
    //4、視頻最大的時間長度  default value is 10 minutes.
    _picker.videoMaximumDuration = 100.f; //100 seconds
    
    [self presentViewController:_picker animated:YES completion:nil];
}


// 調起拍照功能
- (void)fromCamera
{
    //相機功能是否可用,調用相機
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        
        
        //相機訪問權限問題
        if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0) return;
        
         //Available in iOS 7.0 and later.
        AVAuthorizationStatus authstatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authstatus ==AVAuthorizationStatusDenied){
        //用戶關閉了權限
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"用戶關閉了權限" delegate:self cancelButtonTitle:NSLocalizedString(@"OK",@"確定")otherButtonTitles:nil,nil];
            alertView.delegate =self;
            [alertView show];
        }
        else if (authstatus ==AVAuthorizationStatusRestricted){
        //The user is not allowed to access media capture devices.
            
            
        }
        else if (authstatus ==AVAuthorizationStatusNotDetermined){
        //Explicit user permission is required for media capture, but the user has not yet granted or denied such permission.
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if (granted){
                
                    
                }
                else{
                    
                }
            }];
        }
        else if (authstatus ==AVAuthorizationStatusAuthorized){
        //The user has explicitly granted permission for media capture, or explicit user permission is not necessary for the media type in question.
            
            
            _picker = [[UIImagePickerController alloc] init];
            _picker.delegate = (id)self;
            
            //1、默認選項是:UIImagePickerControllerSourceTypePhotoLibrary
            _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
#if 0
            //2-1、針對_picker.sourceType返回所有可用的mediaTypes.
            _picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            /*
             打印這個數組可以看到下邊的結果
            mediaTypes = (
                          "public.image",
                          "public.movie"
                          )
             */
            NSLog(@"mediaTypes = %@",_picker.mediaTypes);
#elif 0
            //2-2、所以還可以這麼設置
//             _picker.mediaTypes = [NSArray arrayWithObject:@"public.image"];
#elif 1
            //2-3、主要是下邊的兩能數,@"public.movie", @"public.image"  一個是錄像,一個是拍照
            _picker.mediaTypes = [NSArray arrayWithObjects:@"public.image",@"public.movie", nil];
#endif
            
            //3、是否允許對獲得的圖片進行編輯,default value is NO.
            _picker.allowsEditing   = YES;
            
            //4、顯示相機的所有控件 默認YES
            _picker.showsCameraControls = YES;
            
            //5、set a view to overlay the preview view類似相框
            _picker.cameraOverlayView = nil;
            
            //6、設定圖像縮放
            _picker.cameraViewTransform = CGAffineTransformScale(_picker.cameraViewTransform, 1.0, 1.0);
            
            //7、拍攝照片的清晰度,只有在照相機模式下可用
            /*
             拍攝照片的清晰度,只有在照相機模式下可用
             enum {
             UIImagePickerControllerQualityTypeHigh = 0,       // 高質量
             UIImagePickerControllerQualityType640x480 = 3,    // VGA quality
             UIImagePickerControllerQualityTypeMedium = 1,     // 中質量,適合於wifi傳輸
             UIImagePickerControllerQualityTypeLow = 2         // 低質量,適合於蜂窩數據傳輸
             };
             typedef NSUInteger UIImagePickerControllerQualityType;
             @property(nonatomic)           UIImagePickerControllerQualityType    videoQuality    //默認選中的是UIImagePickerControllerQualityTypeMedium
             */
            _picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
            
            
            //8、設置照相模式還是攝像模式
            /*
             可以設置照相機的模式,照相還是錄視頻,默認照相模式。
            enum {
                UIImagePickerControllerCameraCaptureModePhoto,//照相模式 默認模式
                UIImagePickerControllerCameraCaptureModeVideo//攝像模式
            };
             typedef NSUInteger   UIImagePickerControllerCameraCaptureMode;
             @property(nonatomic) UIImagePickerControllerCameraCaptureMode    cameraCaptureMode
            */
            _picker.cameraCaptureMode  = UIImagePickerControllerCameraCaptureModePhoto;
            
            //9、使用哪個攝像頭
            /*
             typedef NS_ENUM(NSInteger, UIImagePickerControllerCameraDevice) {
             UIImagePickerControllerCameraDeviceRear,//後置攝像頭
             UIImagePickerControllerCameraDeviceFront//前置攝像頭
             } __TVOS_PROHIBITED;
             */
            _picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            
            //10、設置拍照時閃光燈模式
            /*
            enum {
                UIImagePickerControllerCameraFlashModeOff  = -1, //關閉
                UIImagePickerControllerCameraFlashModeAuto = 0,  //自動
                UIImagePickerControllerCameraFlashModeOn   = 1   //打開
            };
            typedef NSInteger UIImagePickerControllerCameraFlashMode;
            @property(nonatomic) UIImagePickerControllerCameraFlashMode   cameraFlashMode
            */
            _picker.cameraFlashMode = UIImagePickerControllerCameraFlashModeOn;
            
            
            
            [self presentViewController:_picker animated:YES completion:^(){}];

            
        }
    }
    else{
        //如果沒有相機訪問功能,就進行提示
        NSLog(@"沒有相機功能");
    }
}




#pragma mark--點擊相冊中的圖片 貨照相機照完後點擊use  後觸發的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    /* info dictionary keys
     UIImagePickerControllerOriginalImage  // a UIImage
     UIImagePickerControllerEditedImage    // a UIImage
     UIImagePickerControllerMediaURL       // an NSURL
     */
    
    //獲取修改後的圖片
    UIImage * originalImage  = info[UIImagePickerControllerOriginalImage];
    UIImage * editedImg = info[UIImagePickerControllerEditedImage];
    NSURL   * mediaUrl  = info[UIImagePickerControllerMediaURL];
    
    //選中圖片進行了裁剪
    if (editedImg) {
        self.imageView.image = editedImg;
    }
    else{
        //沒有對圖片進行裁剪
        self.imageView.image = originalImage;
    }
    //如果選中的是視頻
    if (mediaUrl) {
        self.imageView.image = nil;
        [self creatMediaPlayerWithUrl:mediaUrl];
    }
    
    //移除圖片選擇的控制器
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark--點擊cancel 調用的方法

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    NSLog(@"取消了操作");
    [self dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark--創建播放器
-(void)creatMediaPlayerWithUrl:(NSURL * )url{
    // 創建播放器
    AVPlayer *player = [AVPlayer playerWithURL:url];
    [player play];
    // 創建播放器圖層
    AVPlayerLayer *layer = [AVPlayerLayer layer];
    layer.player = player;
    layer.frame = self.imageView.bounds;
    // 添加圖層到控制器的view
    [self.imageView.layer addSublayer:layer];
    self.player = player;
}

@end


參考文章:

1、UIImagePickerController使用 - dean19900504的專欄 - 博客頻道 - CSDN.NET

2、

3、







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章