在我的应用程序中,当我使用UIImagePickerController时,我调整从拾取器中获取的图像的大小,以便从它开始的非常大的尺寸减少它。在iPhone和iPod Touch上,它工作正常,并且存在轻微的延迟。但是,由于iPad屏幕要大得多,因此根据像素调整大小,因此需要更长时间。
这是我的代码:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGFloat screenScale = [[UIScreen mainScreen] scale];
CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale);
UIGraphicsBeginImageContext(screenSize);
[image drawInRect:CGRectMake(0,0,screenSize.width,screenSize.height)];
newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
[currentDefaults setObject:UIImagePNGRepresentation(newImage) forKey:@"newImageKey"];
[currentDefaults synchronize];
[popoverController dismissPopoverAnimated:YES];
[picker dismissModalViewControllerAnimated:YES];
}
有没有办法更快地调整大小或以其他方式执行此操作,以便在系统调整大图像大小时用户不会注意到延迟?
谢谢!
答案 0 :(得分:3)
一般来说,我建议你做两件事。首先,考虑使用块来使调整大小和保存操作发生在主线程之外(这需要iOS 4.0及更高版本)。你的方法看起来像这样(在我的头顶而不是编译)
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGFloat screenScale = [[UIScreen mainScreen] scale];
CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale);
UIGraphicsBeginImageContext(screenSize);
[image drawInRect:CGRectMake(0,0,screenSize.width,screenSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
[currentDefaults setObject:UIImagePNGRepresentation(newImage) forKey:@"newImageKey"];
[currentDefaults synchronize];
});
[popoverController dismissPopoverAnimated:YES];
[picker dismissModalViewControllerAnimated:YES];
}
我强烈建议的第二件事是不将结果图像存储在NSUserDefaults中。 NSUserDefaults仅用于小型键值存储。如果要存储图像,请使用NSFileManager将它们存储在磁盘上,并将路径存储为NSUserDefaults中的值。