用户可以选择是使用现有图像还是使用新图像作为背景。
就 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;
}
一定有错误或逻辑错误。帮助将不胜感激!