UIImage seem to only decode data it needs for drawing, but that is not documented anywhere

Originator:michaelhochs
Number:rdar://30460923 Date Originated:10-Feb-2017 09:22 AM
Status:Open Resolved:
Product:Documentation Product Version:iOS 10.2
Classification:Other Bug Reproducible:Always
 
When working on code to draw an image in a tiled style to safe memory, I noticed that drawing a `UIImage` through its `drawInRect:` method onto a graphics context with a clipping mask set, it seems that `UIImage` only decodes the part of the image that it actually needs to draw inside the visible area. This also seems to be the case when using the CoreGraphics API and a `CGImageRef`.

UIKit / CoreGraphics also seem to be very smart about purging that memory when you are drawing different parts of a very large image in a very short time.

This is a very awesome feature as it basically reduces the code to draw an image into a `CATiledLayer` to something like this (inside a `UIView` backed by a `CATiledLayer`):

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGRect scaleToFitRect = AVMakeRectWithAspectRatioInsideRect(self.image.size, self.bounds);
    [self.image drawInRect:scaleToFitRect];
    CGContextRestoreGState(context);
}

As the tiled layer already provides the correct clipping mask, this seems to make the image decode only the region that is necessary.

This seems to work fine, however I don’t think this behavior is documented anywhere in the UIKit or CoreGraphics documentations. That makes it hard to build up on this behavior as there is no public knowledge about whether this behavior is only true for certain formats (if so, which ones?) or if there are any other side conditions that need to be met.

In either way, there seems to be a smart logic controlling the memory use of an image and this should be documented one way or the other.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!