Ios 来自UIPickerController的自定义背景图像

Ios 来自UIPickerController的自定义背景图像,ios,background,Ios,Background,构建一个应用程序,为用户提供更改应用程序背景的选项。 当前正在使用此代码从选择器保存图像 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { customImage = [info objectForKey:UIImagePickerControllerOriginalImage]; NSData

构建一个应用程序,为用户提供更改应用程序背景的选项。 当前正在使用此代码从选择器保存图像

- (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]];

}
在视图中加载

[self performSelector:@selector(fetchCustomBackground)];

目前,应用程序运行速度非常慢,我想是因为每次加载视图时,它都必须获取图像,是否有办法保存它,以便您不必每次加载视图时都调用它?

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

尝试像这样更新您的函数

- (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]];
}); });
}

请注意,这与Xcode完全无关。Xcode只是用来编写iOS应用程序的IDE。另一方面,您的问题纯粹与编程相关。您可以在同一类中调用如下方法:[self-fetchCustomBackground];使用未声明的标识符“数据”现在试试,我不在电脑上,所以我无法检查OK现在工作得很好,速度更快,但是图像在视图后加载一小部分,有什么想法吗?当然,加载图像需要一些时间。现在,主队列没有阻塞,因此它可以在后台加载图像时执行其他一些任务。如果您想在加载背景的情况下加载视图,请尝试缩小背景图片的大小,或者如果不可能,并且您需要大图片,则可以进行某种预加载…什么样的预加载?