1

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

就 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;
}

一定有错误或逻辑错误。帮助将不胜感激!

4

2 回答 2

0

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

+imageNamed:“在应用程序的主包中查找具有指定名称的图像。” (UIImage 参考),但这不是您将其保存到的位置。我不认为您可以写入应用程序的捆绑包,因此您将无法在+imageNamed:此处使用。

于 2010-01-24T21:39:09.933 回答
0

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

我怀疑你想要:

UIImage* image = [UIImage imageWithContentsOfFile:fileNameAndPath];
于 2010-01-24T21:45:40.253 回答