iOS:提高图像绘制速度

时间:2011-07-15 14:06:11

标签: ios calayer quartz-graphics cgcontext

我有一系列想要制作动画的图像(UIImageView支持一些基本的动画,但这还不足以满足我的需要。)

我的第一种方法是使用UIImageView并在图像时设置image属性。这太慢了。速度差的原因是由于图像的绘制(这让我感到惊讶;我认为瓶颈会加载图像)。

我的第二种方法是使用通用UIView并设置view.layer.contents = image.CGImage。这没有明显的改善。

这两种方法都必须在主线程上执行。我认为速度不佳是因为必须将图像数据绘制到CGContext

如何提高绘图速度?是否可以在后台线程上绘制上下文?

2 个答案:

答案 0 :(得分:9)

我设法通过做一些事情来提高绩效:

  • 我修复了构建过程,以便对PNG进行iOS优化。 (应用程序的内容在一个单独的项目中进行管理,该项目输出一个包。默认的包设置是针对OS X包的,它不会优化PNG。)

  • 在后台线程I:

    1. 创建了一个新的位图上下文(下面的代码)
    2. 将PNG图像绘制到位图上下文
    3. 从位图上下文
    4. 创建CGImageRef
    5. 将主线程上的layer.content设置为CGImageRef
  • 使用NSOperationQueue来管理操作。

我确信有更好的方法可以做到这一点,但上述结果会带来可接受的效果。

-(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;
}

答案 1 :(得分:0)

使用UIImageView的内置动画服务使用UIImages *(animationImages)以及附带的animationDuration和animationRepeatCount不能使用的动画要求是什么?

如果您正在快速绘制多个图像,请仔细查看Quartz 2D。如果你正在绘画,然后动画(移动,缩放等)图像,你应该看看核心动画。

听起来像Quartz 2D就是你想要的。 Apple文档在这里: http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/Introduction/Introduction.html

相关问题