我正在为 iPhone 制作一个简单的绘图程序。目前,触摸事件将其位置添加到一个列表中,该列表与一堆 CGContextAddLineToPoint 调用连接,这些调用在每次调用 drawRect 时都会重绘。

我在行数相当少的情况下遇到了性能问题(尽管它们是透明的),所以我尝试将所有内容绘制到 CGLayer 中。现在,它不再每帧绘制每条线,而是每条线仅绘制一次,并每帧将 CGLayer 绘制到屏幕上。

        CGContextRef backgroundContext = CGLayerGetContext(pathBuffer);
        CGContextSetLineWidth(backgroundContext, 2.0);
        CGContextSetLineCap(backgroundContext, kCGLineCapButt);
        CGContextSetStrokeColorWithColor(backgroundContext, [pathColor CGColor]);

        if([[touchPoints objectAtIndex:0] continuesToNextPoint])
        {
            CGContextMoveToPoint(backgroundContext, [[touchPoints objectAtIndex:0] point].x, [[touchPoints objectAtIndex:0] point].y);
            CGContextAddLineToPoint(backgroundContext, [[touchPoints objectAtIndex:1] point].x, [[touchPoints objectAtIndex:1] point].y);
            CGContextStrokePath(backgroundContext);
        }

        //remove it from touchpoints
        [touchPoints removeObjectAtIndex:0];
    }

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawLayerAtPoint(context, CGPointMake(0, 0), pathBuffer);

如果有的话,这比我之前做的要慢。难道我做错了什么?我会更好地绘制 UIImage 或其他东西吗?谢谢。

有帮助吗?

解决方案

你应该做的是插入一个 CALayer 进入您的视图之一,更新图层,然后调用 setNeedsDisplayInRect: 图层上已更改的区域的边界,这会导致其更新。如果您尝试更新整个屏幕,速度会很慢。

您是否使用 Instruments 来找出哪些部分速度慢?我建议使用它来了解哪些部分会减慢您的速度。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top