从文档目录加载图像时,UITableView中的滞后滚动

时间:2012-06-06 04:14:06

标签: iphone uitableview uiimage scroll lag

我有一个UITableView,它显示带有图像及其名称的项目。问题是由于每个单元格的图像加载,滚动滞后。

这就是我保存从iPhone相机捕获的图像并将其调整为320×480的方法。

- (void)saveImage: (UIImage*)image{
if (image != nil)
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *imageName = [NSString stringWithFormat: @"image_%@.png",[NSDate date]];
    item.imageName = imageName;

    NSString* path = [documentsDirectory stringByAppendingPathComponent: 
                      imageName];
    NSLog(@"%@",path);

    NSData* data = UIImagePNGRepresentation(image);
    [data writeToFile:path atomically:YES];

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger:[image imageOrientation] forKey:@"kImageOrientation"];
} }

这就是我调整大小的方法

- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGImageRef imageRef = image.CGImage;

UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();

// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);

CGContextConcatCTM(context, flipVertical);  
// Draw into the context; this scales the image
CGContextDrawImage(context, newRect, imageRef);

// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

CGImageRelease(newImageRef);
UIGraphicsEndImageContext();    

return newImage;}

这就是我在cellForRowAtIndexPath中加载它们的方式

- (UIImage*)loadImage:(NSString *) imageName{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                                     NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent: 
                  [NSString stringWithString: imageName]];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    UIImage *orientedImage= [UIImage imageWithCGImage: image.CGImage scale:1.0 orientation:  [userDefaults integerForKey:@"kImageOrientation"]];

return orientedImage;}

我想到的一种方法是在其中加载一个带有UIImages的NSMutableArray,然后从那里获取图像。该方法的问题在于并非所有单元都有图像所以说最后3个单元中有10个单元但只有3个图像,NSMutableArray方法在这里会有问题,因为添加的图像将位于索引0,1, 2。

我还有一个解决方案,我想在此强调专家验证它是否有效。我实际上正在使用CoreData并为Item生成了Model。如果我要在这个类中手动添加一个UIImage字段并将图像保存到它们的对象中,那么这样做还是错误的呢?

0 个答案:

没有答案