iphone - 为什么 drawRect 中的 CGContextDrawImage 最初很慢?

标签 iphone objective-c ios core-graphics drawrect

考虑一个支持 ARC 的 iOS 应用程序中的这个简单的 UIView 子类,它在触摸屏幕时在 View 上绘制:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    CGPoint location = [[touches anyObject] locationInView:self];

    int padding = brushSize / 2;

    CGRect brushRect = CGRectMake(
        location.x - padding, location.y - padding,
        brushSize, brushSize
    );

    [self setNeedsDisplayInRect:brushRect];

}

- (void)drawRect:(CGRect)rect {

    NSDate *start = [NSDate date];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, rect, brushImage);

    NSLog(@"%f", [start timeIntervalSinceNow]);

}

在这个例子中,brushImage 是一个正方形位图,brushSize 是一个描述位图宽度和高度的整数。

我一直得到这样的日志输出:

-0.131658
-0.133998
-0.143314
-0.007132
-0.006968
-0.007444
-0.006733
-0.008574
-0.007163
-0.006560
-0.006958

对 drawRect 的第一次调用比后续调用需要更长的时间才能完成,此后 drawRect 继续保持快速。只有在 View 初始化后的第一次调用中 drawRect 才慢。

我在模拟器和我尝试过的所有物理设备中都看到了类似的结果。最初的调用总是需要更长的时间才能完成。

为什么 drawRect/CGContextDrawImage 在初始调用时这么慢?更重要的是,我该如何解决这个问题?

最佳答案

检查矩形。我敢打赌前三个是全屏更新。我以前遇到过这个问题。无论你做什么,IOS 都会强制将前几次更新为全屏(可能是因为它的 GL 缓冲系统)。如果你让它单独放置大约 5 秒钟,然后再次绘制一些东西,你将得到相同的行为。我从来没有弄清楚真正的原因是什么,我怀疑我永远不会:(。

看我最初问的问题:UIGraphicsGetCurrentContext() short lifetime

关于iphone - 为什么 drawRect 中的 CGContextDrawImage 最初很慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12505579/

相关文章:

iphone - Android 编程与 iPhone 编程完全不同吗?

iphone - SQLite。不能添加超过 1000 行

ios - 使用Azure移动服务sdk在iOS中并行调用

objective-c - 成员(member)无法在 muc room 中获取成员(member)列表

ios - 有没有办法指定 NSNotifications 的发送者/接收者的粒度?

iphone - 具有自定义上下文菜单选项的 iOS 浏览器应用程序

iphone - 使用AudioFileReadPackets通过Audio Queue访问原始音频数据

iPhone UITextField 在点击时不显示编辑插入符号或清除占位符文本

ios - 带有点击事件的 UITapGestureRecognizer

ios - 使用 nib 的自定义初始化程序?