0

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

这就是我保存从 iPhone 相机拍摄的图像并将其大小调整为 320 x 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;}

我正在考虑的一种方法是让一个 NSMutableArray 加载一次 UIImages,然后从那里获取图像。这种方法的问题在于,并非所有单元格都有图像,所以说有 10 个单元格,但最后 3 个单元格中只有三个图像,NSMutableArray 方法在这里会出现问题,因为添加的图像将位于索引 0,1, 2.

我脑海中还有一个解决方案,我想在这里强调一下,供各位专家验证它是否有效。我实际上正在使用 CoreData 并为项目生成了模型。如果我要在此类中手动添加 UIImage 字段并将图像保存到它们的对象中,那会起作用还是这样做是错误的?

4

0 回答 0