iOS: Improving speed of image drawing

人盡茶涼 提交于 2019-12-03 00:42:38

I managed to improve performance by doing a few things:

  • I fixed my build process so that the PNGs were being iOS optimized. (The content for the app is being managed in a separate project which outputs a bundle. The default bundle settings are for an OS X bundle, which does not optimize PNGs).

  • On a background thread I:

    1. Created a new bitmap context (code below)
    2. Drew the PNG image into the bitmap context
    3. Created a CGImageRef from the bitmap context
    4. Set layer.content on the main thread to the CGImageRef
  • Used an NSOperationQueue to manage the operations.

I'm sure there's a better way of doing this, but the above results in acceptable performance.

-(CGImageRef)newCGImageRenderedInBitmapContext //this is a category on UIImage
{
    //bitmap context properties
    CGSize size = self.size;
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * size.width;
    NSUInteger bitsPerComponent = 8;

    //create bitmap context
    unsigned char *rawData = malloc(size.height * size.width * 4);
    memset(rawData, 0, size.height * size.width * 4);    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();    
    CGContextRef context = CGBitmapContextCreate(rawData, size.width, size.height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    //draw image into bitmap context
    CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), self.CGImage);
    CGImageRef renderedImage = CGBitmapContextCreateImage(context);

    //tidy up
    CGColorSpaceRelease(colorSpace);    
    CGContextRelease(context);
    free(rawData);

    //done!
    //Note that we're not returning an autoreleased ref and that the method name reflects this by using 'new' as a prefix
    return renderedImage;
}

What is it about your animation requirements that make using UIImageView's built-in animation service using an array of UIImages * (animationImages) and accompanying animationDuration and animationRepeatCount not work?

If you are rapidly drawing multiple images, look closely at Quartz 2D. If you are drawing , then animating (moving, zooming, etc) an image, you should be looking at Core Animation.

It sounds like Quartz 2D is what you want. Apple docs here: http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/Introduction/Introduction.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!