iOS 调用相机拍照和选择图库图片 设置头像

来源:互联网 发布:淘宝童学少年儿童家具 编辑:程序博客网 时间:2024/05/17 01:06

不多说,直接上代码


#import "ViewController.h"


@interface ViewController ()<UIImagePickerControllerDelegate,UIActionSheetDelegate>


@property(nonatomic,strong)UIButton *btn;

@property(nonatomic,strong)UIActionSheet *actionSheet;


@end


@implementation ViewController


- (void)viewDidLoad {

[superviewDidLoad];

// 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)

{

case0:

//来源:相机

sourceType = UIImagePickerControllerSourceTypeCamera;

break;

case1:

//来源:相册

sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

break;

case2:

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 = [infoobjectForKey:UIImagePickerControllerOriginalImage];

[_btnsetBackgroundImage:image forState:UIControlStateNormal];

}



- (void)didReceiveMemoryWarning {

[superdidReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}



@end


0 0
原创粉丝点击