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 = [UIButton buttonWithType:UIButtonTypeSystem];

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

_btn.backgroundColor = [UIColor yellowColor];

[_btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

[_btn setTitle:@"點我" forState:UIControlStateNormal];

[self.view addSubview:_btn];

}


- (void)btnClick:(UIButton *)sender

{

[self openActionSheetFunc];

}


//調用ActionSheet

- (void)openActionSheetFunc

{

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

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])

{

_actionSheet = [[UIActionSheet alloc]initWithTitle:@"選擇圖像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"從相冊選擇", nil];

}

else

{

_actionSheet = [[UIActionSheet alloc]initWithTitle:@"選擇圖像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"從相冊選擇", nil];

}

_actionSheet.tag = 100;

//顯示提示欄

[_actionSheet showInView:self.view];

}


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

{

if (actionSheet.tag == 100)

{

NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

if ([UIImagePickerController isSourceTypeAvailable: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 = [[UIImagePickerController alloc]init];

imagePickerController.allowsEditing  = YES;

imagePickerController.sourceType = sourceType;

imagePickerController.delegate = self;

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

}

}


//pickerController的代理

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

{

[picker dismissViewControllerAnimated:YES completion:nil];

UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

[_btn setBackgroundImage:image forState:UIControlStateNormal];

}



- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}



@end


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