#import "RootViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>//此frameWork中预置了一些跟系统资源相关的常量
@interfaceRootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad
{
[superviewDidLoad];
NSArray *array = [NSArrayarrayWithObjects:@"相机",@"相册库",nil];
for (int i=0; i<array.count; i++) {
UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:array[i]forState:UIControlStateNormal];
[btn addTarget:selfaction:@selector(btnClicked:)forControlEvents:UIControlEventTouchUpInside];
btn.tag = i+100;
[btnsetFrame:CGRectMake(10,74+i*40,300,50)];
[self.viewaddSubview:btn];
}
}
//让UIImagePickerController根据不同的type加载不同的资源,UIImagePickerController中封装了相机、相册库等系统资源
- (void)loadSourceWithType:(UIImagePickerControllerSourceType)sourceType{
UIImagePickerController *picker = [[UIImagePickerControlleralloc]init];
picker.sourceType = sourceType;
//1 设置代理@property (nonatomic, assign) id<UINavigationControllerDelegate, UIImagePickerControllerDelegate> delegate。要实现两个协议。
picker.delegate =self;
//是否对相册资源进行自动处理
picker.allowsEditing =YES;
//在程序中,对于picker习惯于通过模态化的方式呈现出来
[selfpresentViewController:pickeranimated:YEScompletion:^{
}];
}
//根据不同的提示信息,创建警告框
- (void)showAlertWithMessage:(NSString *)message{
UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"温馨提示"message:messagedelegate:nilcancelButtonTitle:nilotherButtonTitles:@"确定",nil];
[alertshow];
}
- (void)btnClicked:(UIButton *)btn{
switch (btn.tag) {
case100:
{
//1 先判断资源是否可用
if ([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
[selfloadSourceWithType:UIImagePickerControllerSourceTypeCamera];
}else{
[selfshowAlertWithMessage:@"相机不可用"];
}
}break;
case101:
{
if ([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
[selfloadSourceWithType:UIImagePickerControllerSourceTypePhotoLibrary];
}else{
[selfshowAlertWithMessage:@"无法调用相册库"];
}
}break;
default:
break;
}
}
//点击cancel按钮时,触发此方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:^{}];
}
//选中图片资源时(choose),会触发此方法,info中带有选中资源的信息
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//先判断资源是否为图片资源(可能是video),获取选中资源的类型
NSString *mediaType = [infoobjectForKey:UIImagePickerControllerMediaType];
//kUTTypeImage系统预置的图片类型的常量
if ([mediaTypeisEqualToString:(NSString *)kUTTypeImage]) {
//取到图片
UIImage *image = [infoobjectForKey:UIImagePickerControllerEditedImage];
self.view.backgroundColor = [UIColorcolorWithPatternImage:image];
}
[picker dismissViewControllerAnimated:YES completion:^{}];
}
@end