1. 程式人生 > >iOS 呼叫相機拍照和選擇相簿圖片 設定頭像

iOS 呼叫相機拍照和選擇相簿圖片 設定頭像

不多說,直接上程式碼

#import "ViewController.h"

@interface ViewController ()<UIImagePickerControllerDelegate,UIActionSheetDelegate>

@property(nonatomic,strong)UIButton *btn;

@property(nonatomic,strong)UIActionSheet *actionSheet;

@end

@implementation ViewController

- (void)viewDidLoad {

[super

viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

_btn = [UIButtonbuttonWithType:UIButtonTypeSystem];

_btn.frame = CGRectMake(80, 200, 200, 200);

_btn.backgroundColor = [UIColoryellowColor];

[_btnaddTarget:selfaction:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

[_btnsetTitle:@"點我"forState:UIControlStateNormal];

[self.viewaddSubview:_btn];

}

- (void)btnClick:(UIButton *)sender

{

[selfopenActionSheetFunc];

}

//呼叫ActionSheet

- (void)openActionSheetFunc

{

//判斷裝置是否有具有攝像頭(相機)功能

if ([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])

{

_actionSheet = [[UIActionSheetalloc]initWithTitle:@"選擇影象"delegate:selfcancelButtonTitle:@"取消"destructiveButtonTitle:nilotherButtonTitles:@"拍照",@"從相簿選擇", nil];

}

else

{

_actionSheet = [[UIActionSheetalloc]initWithTitle:@"選擇影象"delegate:selfcancelButtonTitle:@"取消"destructiveButtonTitle:nilotherButtonTitles:@"從相簿選擇", nil];

}

_actionSheet.tag = 100;

//顯示提示欄

[_actionSheetshowInView:self.view];

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

{

if (actionSheet.tag == 100)

{

NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

if ([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])

{

switch (buttonIndex)

{

case 0:

//來源:相機

sourceType = UIImagePickerControllerSourceTypeCamera;

break;

case 1:

//來源:相簿

sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

break;

case 2:

return;

}

}

else

{

if (buttonIndex == 2)

{

return;

}

else

{

sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;

}

}

//跳轉到相機或者相簿頁面

UIImagePickerController *imagePickerController = [[UIImagePickerControlleralloc]init];

imagePickerController.allowsEditing  = YES;

imagePickerController.sourceType = sourceType;

imagePickerController.delegate = self;

[selfpresentViewController:imagePickerController animated:YEScompletion:nil];

}

}

//pickerController的代理

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

{

[picker dismissViewControllerAnimated:YEScompletion:nil];

UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

[_btnsetBackgroundImage:image forState:UIControlStateNormal];

}

- (void)didReceiveMemoryWarning {

[superdidReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end