ios - 在 UIView 上快速绘制 UIImage 图像

标签 ios

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

-(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 设置框架,图像就会显示在您想要的位置和大小,无需重新渲染图像数据。

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

关于ios - 在 UIView 上快速绘制 UIImage 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8912891/

相关文章:

ios - 如何将 Clockify API 与 Siri 快捷方式结合使用

Android TextView 文本截断行为

ios - Facebook iOS SDK - 设置 Controller 的正确方法是什么

ios - 意外的标识符错误 - SpriteKit

ios - 如何从 UITableViewCell 的 UIContextualAction 显示弹出窗口 UIAlertController?

ios - 纯文本在 iOS 底部被截断,如何在 xCode 中修复?

MeteorJS 的 iOS 9 Beta 2 网络问题

ios - 一半屏幕无法点击

iOS:强制 tableView 单元格在点击时动画更改

android - libGDX:FrameBuffer 大小限制 == 最大纹理大小?