如何使用2ndViewController中1stViewController中拍摄的图像?

时间:2010-01-24 21:17:57

标签: iphone xcode sdk uiimagepickercontroller

用户可以选择是否要使用现有图像或使用新图像作为背景。

就FirstViewController而言,一切都有效。遗憾的是,当显示SecondViewController时,图像不再被设置为背景。

如何启用将图像用作SecondViewController的背景?

我使用了这段代码(在SecondViewController中):

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
int bla = [prefs integerForKey:@"background_key"];
if (bla == 1) {
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"1.mac.jpg"]];
} else if (bla == 2) {
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"black.jpg"]];
} else if (bla == 3) {
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pinn.png"]];
} else if (bla == 4) {
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"MyImage.png"]];
}

我尝试将所选图像保存为“MyImage.png”,但看起来好像不起作用。背景为黑色而不是所选图像。

我使用此代码(来自1stViewController)将所选图片保存为“MyImage.png”:

- (void)imagePickerController:(UIImagePickerController *)picker 
    didFinishPickingMediaWithInfo:(NSDictionary *)anInfo {

//UIImage *selectedImage;
NSURL *mediaUrl;

mediaUrl = (NSURL *)[anInfo valueForKey:UIImagePickerControllerMediaURL];
if (mediaUrl == nil)
{
    selectedImage = (UIImage *) [anInfo valueForKey:UIImagePickerControllerEditedImage];
    if (selectedImage == nil)
    {
        selectedImage = (UIImage *) [anInfo valueForKey:UIImagePickerControllerOriginalImage];
        NSLog(@"Original image picked.");
    }
    else
    {
        NSLog(@"Edited image picked.");
    }
}

[picker dismissModalViewControllerAnimated:YES];
if (selectedImage != nil)
{
    self.view.backgroundColor = [UIColor colorWithPatternImage:selectedImage];
}

// Get the image from the result
UIImage* ownImage = [anInfo valueForKey:UIImagePickerControllerOriginalImage];

// Get the data for the image as a PNG
NSData* imageData = UIImagePNGRepresentation(ownImage);

// Give a name to the file
NSString* imageName = @"MyImage.png";

// Now, we have to find the documents directory so we can save it
// Note that you might want to save it elsewhere, like the cache directory,
// or something similar.
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];

// Now we get the full path to the file
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];

// and then we write it out
[imageData writeToFile:fullPathToFile atomically:NO];

return;
}

必定存在错误或逻辑错误。 帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

尝试使用类似的代码加载图像以保存它而不是使用+imageNamed::构建完整路径并从那里加载。

+imageNamed:“在应用程序的主包中查找具有指定名称的图像。” (UIImage reference),但这不是你保存它的地方。我不认为您可以写入应用程序的包,因此您将无法在此处使用+imageNamed:

答案 1 :(得分:0)

ImageNamed通常用于加载作为应用程序资源的一部分包含的图像。

我怀疑你想要:

UIImage* image = [UIImage imageWithContentsOfFile:fileNameAndPath];