[iOS]調用系統相機,相冊,閃光燈

#import
//調用閃光燈調用框架
#import
 
@interface CameraViewController : UIViewController
{
    AVCaptureSession * _AVSession;//調用閃光燈的時候創建的類
}
 
@property(nonatomic,retain)AVCaptureSession * AVSession;
 
@end
在.m的- (void)viewDidLoad裏建立4Button,Camera調用相機、Library調用圖片庫、flashlight打開閃光燈、close關閉閃光燈
//打開相機
-(void)addCarema
{
    //判斷是否可以打開相機,模擬器此功能無法使用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
         
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;  //是否可編輯
        //攝像頭
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentModalViewController:picker animated:YES];
        [picker release];
    }else{
        //如果沒有提示用戶
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"你沒有攝像頭" delegate:nil cancelButtonTitle:@"Drat!" otherButtonTitles:nil];
        [alert show];
    }
}
打開相機後,然後需要調用UIImagePickerControllerDelegate裏的方法,拍攝完成後執行的方法和點擊Cancel之後執行的方法:
//拍攝完成後要執行的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //得到圖片
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //圖片存入相冊
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    [self dismissModalViewControllerAnimated:YES];
     
}
//點擊Cancel按鈕後執行方法
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
}
調用相機照片和保存到圖片庫已經完成。
接着介紹打開照片庫:
-(void)openPicLibrary
{
    //相冊是可以用模擬器打開的
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;//是否可以編輯
 
        //打開相冊選擇照片
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:picker  animated:YES];
        [picker release];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"你沒有攝像頭" delegate:nil cancelButtonTitle:@"Drat!" otherButtonTitles:nil];
        [alert show];
    }
     
}
 
//選中圖片進入的代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [self dismissModalViewControllerAnimated:YES];
}
調用閃光燈的代碼,由於我也不是很理解,所以沒法加註釋,但是已經親測可用,但是調閃光燈時有一個算是bug吧,閃光燈會閒一下,然後再一直亮
-(void)openFlashlight
{
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device.torchMode == AVCaptureTorchModeOff) {
        //Create an AV session
        AVCaptureSession * session = [[AVCaptureSession alloc]init];
         
      
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章