如何提高CGContextDrawPath / drawInContext的速度:

时间:2013-03-13 14:04:58

标签: ios objective-c core-animation core-graphics quartz-core

下面我有以下代码,它基本上是 PieChart 的一个切片,其中包含许多切片。每个切片都在其自己的CALayer中绘制,并使用addSublayer:添加到自定义视图图层。

问题是我正在动态更新饼图,因为用户拖动他们的手指(他们可以通过拖动来编辑饼图值)。它运作良好,但重新绘制这些馅饼'切片'时会有明显的延迟。我看一下iOS Profiling工具,它显示> 50%的时间都在CGContextDrawPath(),因为每次用户移动一定数量的度数时它必须重绘饼图。

我的问题是,我该怎么做才能提高此代码的速度?有什么我想念的吗?

另外作为旁注,这段代码在iPad 2上运行良好(可接受的fps级别),但在iPad 3上它运行得很糟糕,从我的估计来看它慢了2倍。有谁能解释一下?它只是视网膜显示器吗?

-(void)drawInContext:(CGContextRef)ctx {

    // Create the path
    CGRect insetBounds = CGRectInset(self.bounds, self.strokeWidth, self.strokeWidth);
    CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
    CGFloat radius = MIN(insetBounds.size.width/2, insetBounds.size.height/2);

    CGContextBeginPath(ctx);
    CGContextMoveToPoint(ctx, center.x, center.y);

    CGPoint p1 = CGPointMake(center.x + radius * cosf(self.startAngle), center.y + radius * sinf(self.startAngle));
    CGContextAddLineToPoint(ctx, p1.x, p1.y);

    int clockwise = self.startAngle > self.endAngle;
    CGContextAddArc(ctx, center.x, center.y, radius, self.startAngle, self.endAngle, clockwise);

    CGContextClosePath(ctx);

    // Color it
    CGContextSetFillColorWithColor(ctx, self.fillColor.CGColor);
    CGContextSetStrokeColorWithColor(ctx, self.strokeColor.CGColor);
    CGContextSetLineWidth(ctx, self.strokeWidth);

    CGContextDrawPath(ctx, kCGPathFillStroke);
}

1 个答案:

答案 0 :(得分:1)

将图形绘制到iPad 3 Retina显示屏比绘制到iPad 2非Retina更慢。

我记得Apple最初声称iPad 3“比iPad 2快4倍”。似乎并非如此。如果它然后渲染Retina(这是4倍像素)到屏幕应该至少与非视网膜iPad 2相同的速度。

同样的问题发生在Apple发布iPhone 4时.iPhone 4实际上比3GS和3G都要慢。

CoreGraphics slower on iPhone4 than on 3G/3GS

要增加fps,您需要减少drawRect需要绘制的像素数。我建议将你的CoreGraphics相关内容绘制为半分辨率上下文。然后将该上下文作为位图并将其扩展到完整分辨率。但只有在用户拖动时才会这样做。

相关问题