【问题标题】:Why is CGContextDrawImage in drawRect initially slow?为什么 drawRect 中的 CGContextDrawImage 最初很慢?
【发布时间】:2012-09-20 03:07:17
【问题描述】:

考虑一下在启用 ARC 的 iOS 应用中这个简单的 UIView 子类,它会在触摸屏幕时在视图上进行绘制:

- (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 是一个描述位图宽度和高度的 int。

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

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

对 drawRect 的第一次调用比后续调用花费更长的时间来完成,并且 drawRect 此后继续保持快速。只有在视图初始化后的第一次调用时,drawRect 才会很慢。

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

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

【问题讨论】:

    标签: iphone objective-c ios core-graphics drawrect


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!事实上,iOS 在最初的几次调用中重绘了整个视图。欣赏答案。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 2019-10-02
    • 2010-10-30
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多