ios中相機選擇

在我們現在越來越多的應用使用相機功能,今天就簡單介紹一下相機功能和從圖庫選取照片

在ViewdidLoad中

self.imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(20, 40, 60, 60)];
_imageView.backgroundColor = [UIColor greenColor];
_imageView.userInteractionEnabled =YES;
//設置圓角
_imageView.layer.cornerRadius = 30;
_imageView.layer.masksToBounds = YES;
//自適應圖片寬高的比例
_imageView.contentMode = UIViewContentModeScaleAspectFill;

[aView addSubview:_imageView];

//輕拍頭像
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
[_imageView addGestureRecognizer:tap];

實現功能

//處理輕拍事件
-(void)handleTap: (UITapGestureRecognizer *)tap {
//判斷相機是否可用
BOOL isAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
if (isAvailable) {
//相機可用 或系統圖庫
[self setPhotoWithCamera:YES];
}else {
//圖庫選擇
[self setPhotoWithCamera:NO];

}

}
//設置頭像 判斷相機是否可用
- (void)setPhotoWithCamera:(BOOL)isAvailable {
UIAlertController *alert ;
alert = [UIAlertController alertControllerWithTitle:@”select” message:@”photo” preferredStyle:UIAlertControllerStyleActionSheet];
__block LeftViewController *vc =self;
UIAlertAction *action1 = [UIAlertAction actionWithTitle:@”拍照” style:UIAlertActionStyleDefault handler:^(UIAlertAction *action ){
[vc pickImageWithType:UIImagePickerControllerSourceTypeCamera];

}];


UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"從圖庫選擇" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    //跳轉到相冊
    [vc pickImageWithType:UIImagePickerControllerSourceTypePhotoLibrary];

}];
UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
if (isAvailable) {
    [alert addAction:action1];
}

[alert addAction:action2];
[alert addAction:action3];

[self presentViewController:alert animated:YES completion:nil];

}

-(void)pickImageWithType: (UIImagePickerControllerSourceType )SourceType {
UIImagePickerController *controller = [[UIImagePickerController alloc]init];
controller.delegate = self;
controller.allowsEditing = YES;
controller.sourceType = SourceType;
[self presentViewController:controller animated:YES completion:nil];

}

//choose
- (void)imagePickerController:(UIImagePickerController )picker didFinishPickingMediaWithInfo:(NSDictionary )info {
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
self.imageView.image =image;

}
//cancel 選中圖片讓圖片顯示
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[picker dismissViewControllerAnimated:YES completion:nil];

}

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