我可以从图库中选择一个图像并放在Imageview中,但后来我无法将其固定到位

时间:2015-08-08 23:32:20

标签: ios image delegates photo galera

我可以从图库中选择一个图像并放置在ImageView中,但稍后在更改viewController时我无法将其保持到位并返回图像消失

-(IBAction)LibraryPicture
{
if([UIImagePickerController isSourceTypeAvailable:
    UIImagePickerControllerSourceTypePhotoLibrary])
{
    UIImagePickerController *picker= [[UIImagePickerController  alloc]init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:picker animated:YES];

  }
  NSString  *pngPath = [NSHomeDirectory()  stringByAppendingPathComponent:@"Documents/Test.png"];
NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];


                }

 -(void)imagePickerController:(UIImagePickerController *)picker
  didFinishPickingImage : (UIImage *)image
             editingInfo:(NSDictionary *)editingInfo
{
 imageSelect.image = image;
 [picker dismissModalViewControllerAnimated:YES];

}


 -(void)imagePickerControllerDidCancel:(UIImagePickerController *)  picker
 {
[picker dismissModalViewControllerAnimated:YES];
 }

- (BOOL)shouldAutorotateToInterfaceOrientation:     (UIInterfaceOrientation)interfaceOrientation
 {

 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 - (IBAction)saveImage:(id)sender {

  NSLog(@"save image & Keep");
  }

此图像应该保留,直到用户再次更改

1 个答案:

答案 0 :(得分:0)

之所以会这样,是因为你没有保存图片。在您保存图像的IBAction中,您什么都不做。因此,您需要保存图像,然后在viewdidload中(当用户返回VC时),加载该图像。

要保存它,您需要这样做:

NSString *imgName= @"imgname.png";
[[NSUserDefaults standardUserDefaults]setValue:imgName forKey:@"imageName"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:imgName];
UIImage *imageSave = image; // The imageView that you want to save
NSData *imageData = UIImagePNGRepresentation(imageSave);
[imageData writeToFile:savedImagePath atomically:NO];

要在返回该VC时重新加载图像,请在viewDidload中执行以下操作:

NSString *imgName= [[NSUserDefaults standardUserDefaults]valueForKey:@"imageName"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDir,imgName];
[BackGround setImage:[UIImage imageWithContentsOfFile:filePath]];