2010-05-19 47 views
0

似乎這些解決方案都沒有消除與將圖像呈現在屏幕上有關的延遲(無論是來自.png還是使用CG)。呈現數百個「塊」圖像-vs-部分呈現塊的「地圖」

有一個28x16的網格塊,每個網格塊都是16x16像素,並且在遊戲中的某些點,其中大約一半需要因狀態改變而改變其圖像。當每個塊作爲主視圖的子視圖時,其中一半需要單獨更改其圖像(無論是來自.png還是使用CG),都會導致滯後。

我試圖具有一個「映射」視圖,其drawRect:方法是:

CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextClearRect(context, rect); 

// width and height are defined as the width and height of the grid (28x16 for iPhone) 
for (int x = 0; x < width; x++) { 
    for (int y = 0; y < height; y++) { 
     // states[] is an enum instance variable that holds the states of each block in the map (state determines image) 
     if (states[(x * height) + y] == PXBlockStateEmpty) { 
      CGContextSetFillColorWithColor(context, [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:0.5].CGColor); 
      CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5].CGColor); 
      CGContextAddRect(context, CGRectMake(x * 16, y * 16, 16, 16)); 
      CGContextDrawPath(context, kCGPathFillStroke); 
     } else if (states[(x * height) + y] == PXBlockStateSolid || states[(x * height) + y] == PXBlockStateSolidEdge) { 
      CGContextSetFillColorWithColor(context, [UIColor colorWithRed:0.0 green:0.0 blue:102.0/255.0 alpha:0.9].CGColor); 
      CGContextSetStrokeColorWithColor(context, [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.5].CGColor); 
      CGContextAddRect(context, CGRectMake(x * 16, y * 16, 16, 16)); 
      CGContextDrawPath(context, kCGPathFillStroke); 
     } else if (states[(x * height) + y] == PXBlockStateBuilding) { 
      CGContextSetFillColorWithColor(context, [UIColor colorWithRed:51.0/255.0 green:51.0/255.0 blue:51.0/255.0 alpha:0.5].CGColor); 
      CGContextFillRect(context, CGRectMake(x * 16, y * 16, 16, 16)); 
     } 
    } 
} 

所以我的解決辦法是調用setNeedsDisplayInRect:在地圖上,使所述框架(16×16矩形),其塊的狀態改變了。我使用setNeedsDisplayInRect:錯誤地,或者這只是一個低效率的方式來做到這一點?

當許多電路板充滿不同的圖像時,兩種選擇(一種子視圖與幾百種子視圖)滯後一段時間,第二種解決方案特別落後於任何塊的圖像需要更新。

任何想法?感謝您的幫助!

回答

1

調用setNeedsDisplayInRect:影響drawRect的參數:但在其他方面與setneedsDisplay相同。矩形drawRect:receiving是所有髒矩形的聯合。如果只繪製與該矩形相交的內容,而不改變其他內容,則可能會看到速度提高。從上面的代碼片斷中可以看出,每次都會繪製每個瓦片。既然它是一個工會,你也可以單獨跟蹤髒磚,只畫髒磚。在這種情況下,調用CGContextClearRect來獲取單個切片,而不是清除整個上下文,除非它們都是髒的。

CGContextAddRect向將要繪製的路徑添加一個矩形。由於您在每個循環中繪製路徑而不開始新路徑,因此隨着循環的進行重繪區域。使用CGContextFillRect和CGContextStrokeRect代替路徑可能會更快。

使每個tile成爲一個單獨的UIView比整體繪製產生更多的開銷。一旦發現問題,你應該能夠從這種方法中獲得更好的速度。

+0

什麼是「髒矩形」?我不明白你的答案的第一段:( – 2010-05-19 17:10:54

+0

http://developer.apple.com/mac/library/documentation/cocoa/conceptual/CocoaViewsGuide/Optimizing/Optimizing.html 想通了!謝謝指點我朝着正確的方向前進! – 2010-05-19 17:22:11