[英]CGContext does not update immediately
問題:我有一個小游戲,您可以在另一個圖像上方刮擦一個圖像。 上面的圖像在您抓撓的地方變得不可見。 整個過程都放在SpriteKit視圖中。 問題是,在功能較弱的設備(iPhone4)上,僅當用戶停止抓取時才更新抓取圖像。
我假設僅當用戶在圖像完全渲染和顯示之前不會刮擦時才更新圖像。
有人可以建議一種更好的方式立即查看划痕嗎? 我知道抓痕會消耗很多性能,但是我不介意它是否滯后一些。
這里的代碼:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
UIGraphicsBeginImageContext(self.view.frame.size);
[_scratchImage drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), _lastPoint.x, _lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 25.0f );
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
CGContextSetBlendMode (UIGraphicsGetCurrentContext(), kCGBlendModeClear);
CGContextStrokePath(UIGraphicsGetCurrentContext());
_scratchImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
_lastPoint = currentPoint;
SKTexture* scratchTexture = [SKTexture textureWithImage:_scratchImage];
_scratchSprite.texture = scratchTexture;
}
UPDATE
我最終按照正確答案中的建議記錄了要點。 但是除了更新CADisplayLink回調中的圖像外,我還更新了
-(void)update(float currentTime)
從SpriteKit回調(對於SpriteKit用例來說是相同的)
我在update方法中的代碼如下所示:
-(void)displayUpdated
{
UIGraphicsBeginImageContext(self.view.frame.size);
[_scratchImage drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGMutablePathRef linePath = nil;
linePath = CGPathCreateMutable();
CGPathMoveToPoint(linePath, NULL, _lastPoint.x, _lastPoint.y);
for (NSValue* val in _recordedPoints) {
CGPoint p = [val CGPointValue];
CGPathAddLineToPoint(linePath, NULL, p.x, p.y);
NSLog(@"%f, %f", p.x, p.y);
_lastPoint = p;
}
//flush array
[_recordedPoints removeAllObjects];
CGContextAddPath(UIGraphicsGetCurrentContext(), linePath);
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 25.0f );
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0);
CGContextSetBlendMode (UIGraphicsGetCurrentContext(), kCGBlendModeClear);
CGContextStrokePath(UIGraphicsGetCurrentContext());
_scratchImage = UIGraphicsGetImageFromCurrentImageContext();
CGPathRelease(linePath);
UIGraphicsEndImageContext();
SKTexture* scratchTexture = [SKTexture textureWithImage:_scratchImage];
_scratchSprite.texture = scratchTexture;
}
性能更高的代碼還將保留對上下文的引用,但我無法設法使它正常工作。 如果有人可以提出解決方案,我會很高興。 不過,我在iPhone 4上的幀速率從約5 fps升至25-30 fps。
我對SpriteKit不太了解,在UIView中,應該將繪圖代碼放在drawRect方法中。 和SpriteKit一樣嗎?
我會嘗試以下方法:
[_scratchImage drawInRect:...]
。 UIImage
。 合並筆划的線條可能更好,這樣就不會經常創建UIImage
。 例如,將線段放入隊列中,並從CADisplayLink中繪制回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.