在应用程序中,我制作了一个图像视图,其中包含从手机库中选择的图像或由相机拍摄的图像。但是当我回到上一个场景时,选择的图像就消失了。我希望它保存在图像视图中,并有一个清除按钮来删除它。相机功能有效但图像不会保留在图像视图中。
相机功能: .h文件
@interface FMEImageView : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate> {
IBOutlet UIImageView *ImageView;
UIImagePickerController *picker;
UIImage *image;
}
- (IBAction)Takephoto:(id)sender;
- (IBAction)Chosenphoto:(id)sender;
@end
.m文件
- (IBAction)Takephoto:(id)sender{
picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:picker animated:YES completion:NULL];
}
- (IBAction)Chosenphoto:(id)sender{
picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
[picker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:picker animated:YES completion:NULL];
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
[ImageView setImage:image];
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissViewControllerAnimated:YES completion:NULL];
}
答案 0 :(得分:0)
您可能每次都在使用新实例。初始化后使用相同的实例。
答案 1 :(得分:0)
我认为,您必须将图像保存到应用程序的文档目录中。
获取图像数据。
NSData *imgData = UIImagePNGRepresentation(image);
将其写入文件目录。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"];//Choose name for the image.
[imgData writeToFile:filePath atomically:YES]; //Write the file
获取数据并将其显示在imageView上。
再次,获取filePath。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"];//Name you have given
NSData *imgData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:imgData];
imageView.image = image;
最好创建一个函数来获取文档目录的路径。
我希望它有所帮助。