简体   繁体   中英

UIImage drawInRect: is very slow; is there a faster way?

This does exactly what it needs to, except that it takes about 400 milliseconds, which is 350 milliseconds too much:

 - (void) updateCompositeImage { //blends together the background and the sprites
    UIGraphicsBeginImageContext(CGSizeMake(480, 320));

    [bgImageView.image drawInRect:CGRectMake(0, 0, 480, 320)];

    for (int i=0;i<numSprites;i++) {
        [spriteImage[spriteType[i]] drawInRect:spriteRect[i] blendMode:kCGBlendModeScreen alpha:spriteAlpha[i]];
    }

    compositeImageView.image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
}

The images are fairly small, and there are only three of them (the for loop only iterates twice)

Is there any way of doing this faster? While still being able to use kCGBlendModeScreen and alpha?

you can:

  • get the UIImages' CGImages
  • then draw them to a CGBitmapContext
  • produce an image from that

using CoreGraphics in itself may be faster. the other bonus is that you can perform the rendering on a background thread. also consider how you can optimize that loop and profile using Instruments.

other considerations:

  • can you reduce the interpolation quality?
  • are the source images resized in any way (it can help if you resize them)

drawInRect is slow. Period. Even in small images it's grossly inefficient.

If you are doing a lot of repeat drawing, then have a look at CGLayer, which is designed to facilitate repeat-rendering of the same bits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM