2014-02-19 152 views
0

我正在實現以下圖形drawRect函數,但它使用了超過50%的CPU - 關於如何解決這個問題的任何想法?我只畫了幾條隨機線,但我希望它們都有不同的寬度。使用太多CPU的核心圖形

- (void)drawRect:(CGRect)rect 
{ 

    [super drawRect:rect]; 

    @autoreleasepool { 

     CGContextRef context = UIGraphicsGetCurrentContext(); 
     CGMutablePathRef path = CGPathCreateMutable(); 



     float width = rect.size.width; 
     int nbLine=10; // i want to draw 10 paths 

     for (int iLine=1;iLine<nbLine;iLine++){ 

      float Pathwidth=0.8*(nbLine-(float)iLine)/nbLine; 
      CGContextBeginPath(context); 
      CGContextSetLineWidth(context, Pathwidth); //each path should have its own width 
      CGPathMoveToPoint(path, NULL, 0,0); 

      for (int i=0;i<10;i++){ 
       float x=width/(i+1); 
       float y=1;//for this example, I just put a fixed number here - it's normally an external variable 
       CGPathAddQuadCurveToPoint(path, NULL, x+width/10, y, x,0); 


      } 

      CGContextAddPath(context, path); 
      CGContextStrokePath(context); 
     } 

     CGPathRelease(path); 

    } 
} 

謝謝!

+0

繪圖應該最大化CPU。圖紙需要多長時間? –

+0

是否有你擁有'@ autoreleasepool'的理由? – Gavin

+0

@autoreleasepool沒有理由(只是一個測試)。它的繪製速度非常快,並且在每個週期都正確更新(我相信每4ms) –

回答

0

有幾件事你可以嘗試。

  1. 使用儀器找出哪些線正在使用CPU。
  2. 在UIBezierPath中構建一次路徑,然後每次在drawRect中繪製它們。
  3. 看看setNeedsDisplay從哪裏被調用。最有可能每次繪製它都沒有使用太多的CPU。問題很可能是它正在快速反覆繪製。
+0

- 每條路徑都不相同(實際上只是其他路徑的同一性)。然後setNeedsDisplay被這樣調用: - (void)startDisplayLink { _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink :)]; [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; } - (無效)handleDisplayLink:(CADisplayLink *)的DisplayLink { [自setNeedsDisplayInRect:self.bounds]; } –

0

如果按性能可以使用GLKView。核心繪圖基於OpenGL,爲圖形清晰度和質量設置了大量優化。但是,如果這些選項讓你放慢到非可用性的地步,那麼這可能是你最好的選擇。

我的第二個建議是不經常打電話。你說它每4毫秒被調用一次,每秒250次。用戶看不到細節的細節,所以這是很奢侈的。

我的第三個建議是使用UIView,繪製一次,然後根據你的y變量修改它的變換。看起來好像你可以做一個簡單的y縮放來實現你想要做的事情(沒有x變化,沒有線條變化的寬度(繪製一次後))。基於你的代碼,我可能會過度簡化,但嘗試一下會是一件好事。如果y比例變換過大,您也可以混合使用此建議和代碼並重繪。

+0

我的錯誤,它被設置在每40毫秒,而不是4ms,仍然在殺死CPU ......我更擔心該應用程序殺死電池......我會嘗試UIView的伎倆 - 但似乎成本最高的CPU是事實,每個補丁必須有不同的寬度... –