有一个 插入图片按钮,响应函数为:
- (IBAction)insertPhoto:(id)sender {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"插入图片" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"系统相册",@"拍摄", nil];
[alert show];
[alert release];
}
弹出一个对话框,让用户选择图片的来源,是自己拍摄还是通过系统相册插入。
对话框的代理函数为:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSLog(@"index = %d",buttonIndex);
if (buttonIndex == 1)
{
[self addPhoto];
}
else if(buttonIndex == 2)
{
[self takePhoto];
}
}
确定用户选择的图片来源方式。选择1,调用addPhoto从相册读取图片。选择2,调用takePhoto让用户自己拍摄一张图片。
-(void)addPhoto{
//初始化UIImagePickerController对象
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
//设置图片的来源方式为从图片库中,图片的来源方式有3种:
//UIImagePickerControllerSourceTypeCamera让用户照一张照片
//UIImagePickerControllerSourceTypePhotoLibrary让用户选择一个相册,然后从相册选择一张图片
//UIImagePickerControllerSourceTypeSavedPhotosAlbum让用户从最近拍摄的照片中选择一张
[imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
//设置代理,选择完或者取消的时候调用代理方法
[imagePickerController setDelegate:self];
//把相册视图展现出来
[self presentModalViewController:imagePickerController animated:YES];
[imagePickerController release];
}
-(void)takePhoto{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
//确定设备是否支持照相功能,如支持,设置来源为相机等等。如果不是,弹出警告匡
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
[imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera];
[imagePickerController setDelegate:self];
[self presentModalViewController:imagePickerController animated:YES];
}
else{
UIAlertView *aler = [[[UIAlertView alloc]initWithTitle:@"Sorry" message:@"该设备不支持拍照功能" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]autorelease];
[aler show];
aler.delegate = nil;
}
[imagePickerController release];
}
代理方法,当选择好图片后调用,显示选中的图片:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
self.imageView.image = image;
[picker dismissModalViewControllerAnimated:YES];
}
测试:把一张照片加入到相册中,
- (IBAction)savePhoto:(id)sender {
UIImage *image = [UIImage imageNamed:@"ZGR.jpg"];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}