Custom UITableViewCell with large UIImageView causing scroll lag

前端 未结 1 1410
醉话见心
醉话见心 2020-12-23 12:33

I have a custom UITableViewCell that consists of a UIImageView and a UILabel. The cell is 320x104px and the imageView takes up the whole area with the label in front. There

相关标签:
1条回答
  • 2020-12-23 13:15

    Do you load images from local files by any chance?

    By using Instruments I've found that there is some lazy loading mechanism in UIImage - the real image data was decompressed from PNG only at the stage of rendering it on the main thread which caused the lag during scrolling.

    So, after the loading of UIImage with -initWithContentsOfFile: method, I've added code to render the contents of this image to offscreen context, saved that context as new UIImage and used it for UIImageView in UITableViewCell, this made the scroll to be smooth and pleasant to the eye again.

    In case of reference there is the simple code I'm using to force reading of image contents in separate thread (using ARC):

    UIImage *productImage = [[UIImage alloc] initWithContentsOfFile:path];
    
    CGSize imageSize = productImage.size;
    UIGraphicsBeginImageContext(imageSize);
    [productImage drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    productImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    And I think the surface of UIImage created in such a way will be in the supported format suited for rendering, which will also offload work needed to render it on main thread.

    EDIT: The docs for UIGraphicsGetImageFromCurrentImageContext() say that it should be only used from main thread, but searching on the net or SO shows that starting from iOS 4 the UIGraphics.. methods became thread safe.

    0 讨论(0)
提交回复
热议问题