0
我正在嘗試創建一種使用蛇的遊戲。到目前爲止,我得到了它的工作,它很好地工作,但過了一段時間它會有點滯後,特別是在iPhone 5和更低。優化DrawRect:對於Snake排序的遊戲
我知道這是因爲drawRect中的:
-(void) drawRect:(CGRect)rect{
NSDate *start = [NSDate date];
CGFloat rr, rg, rb, ra;
[redcolorr getRed:&rr green:&rg blue:&rb alpha:&ra];
CGFloat gr, gg, gb, ga;
[greencolorr getRed:&gr green:&gg blue:&gb alpha:&ga];
CGFloat br, bg, bb, ba;
[bluecolorr getRed:&br green:&bg blue:&bb alpha:&ba];
if ([myName isEqual:@"Server"]) {
for (int i= 0; i<ServerBody.count; i++) {
Snake *a;
a = [ServerBody objectAtIndex:i];
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(ctx);
CGContextSetRGBFillColor(ctx, rr, rg, rb, ra);
CGContextFillEllipseInRect(ctx, CGRectMake(a.x,a.y,7.5*k*sizee, 7.5*k*sizee));
UIGraphicsPopContext();
}
}
else{
for (int i= 0; i<IntelligentServerBody.count; i++) {
Snake *a;
a = [IntelligentServerBody objectAtIndex:i];
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(ctx);
CGContextSetRGBFillColor(ctx, rr, rg, rb, ra);
CGContextFillEllipseInRect(ctx, CGRectMake(a.x, a.y, 7.5*k*sizee, 7.5*k*sizee));
UIGraphicsPopContext();
}
}
if ([myName isEqual:@"Client0"]) {
for (int i= 0; i<Client0Body.count; i++) {
Snake *a;
a = [Client0Body objectAtIndex:i];
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(ctx);
CGContextSetRGBFillColor(ctx, br, bg, bb, ba); // white color
CGContextFillEllipseInRect(ctx, CGRectMake(a.x, a.y, 7.5*k*sizee, 7.5*k*sizee));
UIGraphicsPopContext();
}
}
else{
for (int i= 0; i<IntelligentClient0Body.count; i++) {
Snake *a;
a = [IntelligentClient0Body objectAtIndex:i];
CGContextRef ctx = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(ctx);
CGContextSetRGBFillColor(ctx, br, bg, bb, ba); // white color
CGContextFillEllipseInRect(ctx, CGRectMake(a.x, a.y, 7.5*k*sizee, 7.5*k*sizee));
UIGraphicsPopContext();
}
}
NSTimeInterval timeInterval = [start timeIntervalSinceNow];
}
記住:
- 的drawRect被稱爲每0.05秒,以重繪兩條蛇
- 有一臺服務器,第一代iPhone,和一個客戶端,第二個iphone(multipeer)
所以現在,請告訴我,如果我不是米發行代碼行,或者有不必要的行。 有沒有其他的方式來繪製蛇?我想讓蛇「發光」(改變每個畫的顏色),也許「增長/縮小」(改變溺水點的大小)。
那麼'UIGraphicsPush/Pop'調用對於一個是多餘的......儘管'drawRect:'不利用GPU,但經常調用它時總會有點遲緩。您可能應該考慮嘗試使用[Core Animation](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreAnimation_guide/Introduction/Introduction.html)或[ Sprite Kit](https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Introduction/Introduction.html),因爲兩者都利用GPU,所以效率更高。 – Hamish
是的,你並不是真的想要使用這樣的重複繪製調用,你正在每個刷新間隔創建一個圖形上下文。例如,您可以通過爲每個蛇創建小「片段」,然後使用SpriteKit通過片段組合來渲染它們,從而獲得更好的結果。這樣,每個細分都是以最佳方式渲染的GPU紋理。您需要編寫代碼來使用X,Y座標和角度連接段,而不是使用此繪製邏輯,但需要進行一些重構,但這樣可以更好地使用圖形子系統。 – MoDJ