调用相机/相册的方法其实很简单,直接上代码。
UIActionSheet *sheet;//先定义一个Actiongsheeet
if ( [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] ) {//判断相机是否可用
sheet = [[UIActionSheet alloc] initWithTitle:@"Please choose!" delegate:self cancelButtonTitle:@"Cancle" destructiveButtonTitle:nil otherButtonTitles:@"Photo Album",@"Camera", nil];
}else{
sheet = [[UIActionSheet alloc] initWithTitle:@"Please choose" delegate:self cancelButtonTitle:@"Cancle" destructiveButtonTitle:nil otherButtonTitles:@"Photo Album", nil];
}
sheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
[sheet showInView:self.view];
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
UIImagePickerController *pick = [[UIImagePickerController alloc] init];
pick.delegate = self;//设置代理,前面要遵守UINavigationControllerDelegate, UIImagePickerControllerDelegate两个协议
if (buttonIndex == 0) {
pick.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//resourceType决定是调出相机还是选择相册
[self presentViewController:pick animated:YES completion:nil];
}
if (buttonIndex == 1) {
if ([actionSheet.title isEqualToString:@"Please choose"]) {
}else{
pick.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:pick animated:YES completion:nil];
}
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info//imagePickview的协议
{
UIImage *img = [info objectForKey:@"UIImagePickerControllerOriginalImage"];//这样就可以把图片取出来了,最后返回原页面,可以打印一下info
//然后可以根据自己的需要决定是否需要压缩一下图片
[self scleToSize:img size:CGSizeMake(100,100)];
[picker dismissViewControllerAnimated:YES completion:nil];
}
<pre>- (UIImage *)scaleToSize:(UIImage *<span style="color:#000000;">)img size:(CGSize)size{ //图片压缩 </span><span style="color:#008000;"> </span>
<span style="color:#000000;"> UIGraphicsBeginImageContext(size); //取得bitmap的context</span><span style="color:#008000;"> </span>
[img drawInRect:CGRectMake(<span style="color:#800080;">0</span>,<span style="color:#800080;">0</span><span style="color:#000000;">, size.width, size.height)];//设置新图片的大小 </span><span style="color:#008000;"> </span>
UIImage* scaledImage =<span style="color:#000000;">UIGraphicsGetImageFromCurrentImageContext(); //生成图片 </span><span style="color:#008000;"> </span>
<span style="color:#000000;"> UIGraphicsEndImageContext(); //结束编辑 </span><span style="color:#008000;"> </span>
<span style="color:#0000ff;">return</span><span style="color:#000000;"> scaledImage; //返回图片
} </span>