构建一个应用程序,让用户可以选择更改应用程序的背景。 目前使用此代码保存选择器中的图像。
- (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)];
目前应用程序非常慢,我猜是因为每次加载视图都需要获取图像,有没有办法保存它,所以你不必每次加载视图时调用它?
答案 0 :(得分:0)
我发现从Documents加载单张图片没问题。但可以肯定的是,如果您正在加载大图并同时执行一些UI更新,则可能会出现问题。你必须使用Grand Central Dispatch释放主线程。
答案 1 :(得分: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]];
}); });
}