1

构建一个应用程序,让用户可以选择更改应用程序的背景。当前使用此代码从选择器中保存图像。

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    customImage = [info objectForKey:UIImagePickerControllerOriginalImage];

    NSData *data = UIImagePNGRepresentation(customImage);
    NSString *fetchCustomImage = @"userCustomImage.png";
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [path objectAtIndex:0];
    NSString *fullPathToFile = [documentDirectory stringByAppendingPathComponent:fetchCustomImage];

    [data writeToFile:fullPathToFile atomically:YES];

    [self dismissViewControllerAnimated:YES completion:NULL];

    [self performSelector:@selector(fetchCustomBackground)]
}

然后调用一个void来显示图像

- (void)fetchCustomBackground
{
    //Fetch Background Image
    NSString *fetchUserImage = @"userCustomImage.png";
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [path objectAtIndex:0];
    NSString *fullPath = [documentDirectory stringByAppendingPathComponent:fetchUserImage];
    NSData *data = [NSData dataWithContentsOfFile:fullPath];
    [background setImage:[UIImage imageWithData:data]];

}

在 viewDidLoad

[self performSelector:@selector(fetchCustomBackground)];

目前该应用程序非常慢,我猜是因为每次加载视图时都必须获取图像,有没有办法保存它,这样您就不必每次加载视图时都调用它?

4

2 回答 2

0

我认为从 Documents 加载单张图片没有问题。但可以肯定的是,如果您正在加载一张大图片并同时进行一些 UI 更新,那可能是个问题。您必须使用 Grand Central Dispatch 释放主线程。

于 2013-07-26T20:26:48.053 回答
0

尝试像这样更新您的功能。

- (void)fetchCustomBackground
{

dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{

__block NSData *data;

dispatch_sync(concurrentQueue, ^{ 
    //Fetch Background Image
    NSString *fetchUserImage = @"userCustomImage.png";
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [path objectAtIndex:0];
    NSString *fullPath = [documentDirectory stringByAppendingPathComponent:fetchUserImage];
    data = [NSData dataWithContentsOfFile:fullPath];
});
dispatch_sync(dispatch_get_main_queue(), ^{
[background setImage:[UIImage imageWithData:data]];
}); });
}
于 2013-07-26T20:36:30.133 回答