在UIView上快速绘制UIImage图像



在我的应用程序中,我必须在视图上实时绘制一些图像,这些图像的位置和缩放比例会随着时间的推移而频繁变化。这些图像是字典中包含的图像的子集。下面是代码,有点总结:

-(void)drawObjects:(NSArray*)objects withImages:(NSDictionary*)images <etc>
{
    // Get graphic context and save it
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    // Display objects in reverse order
    for (int i = [objects count] - 1; i >= 0; i--) {
        MyObject *object = [objects objectAtIndex:i];
        // Check if object shall be visible
        if (<test to check whether the image shall be visible or not>) {
            // Get object image
            UIImage* image = <retrieve image from "images", based on a key stored in "object">;
            // Draw image
            float x = <calculate image destination x>;
            float y = <calculate image destination y>;
            float imageWidth = <calculate image destination width>;
            float imageHeight = <calculate image destination height>;
            CGRect imageRect = CGRectMake(x - imageWidth / 2, y - imageHeight / 2, imageWidth, imageHeight);
            [image drawInRect:imageRect];
        }
    }
    // Restore graphic context
    CGContextRestoreGState(context);
}

我的问题是这个代码很慢;当图像数量大约为15(iPhone 4,iOS 4.3.5)时,执行循环大约需要700到800毫秒。我做了一些实验,似乎瓶颈是drawInRect调用,因为如果我排除它,一切都会以戏剧化的方式加速。

有人提出建议吗?

问题是(我认为)您实际上是在绘制(创建屏幕表示)每一帧中的图像,因为drawInRect:不知道您想要重用上一帧中显示的图像。但你不需要。您只需要绘制一次,然后对其进行变换以更改其位置和大小。

UIKit为您提供了方便:只需为UIImageView设置帧,图像就会显示在您想要的位置和大小,而无需重新渲染图像数据。

您可能可以通过存储UIImageViews本身来进一步优化这一点,这样它们就不必每次需要显示时都重新创建。Istead只是相应地设置了他们的hidden属性。

您的首要答案是:运行Instruments,看看这其中的哪些部分实际上需要时间。(是的,很可能是drawInRect:但也可能是你没有展示的"获取图像")。

最新更新