friend 们,我正在使用 UIBezierPaths 进行自由手绘,一切正常,为此我将我的路径存储在路径数组中,一切正常,在渲染时,我循环整个数组并渲染路径,但是随着数组数量的增加,我在绘图时看到了滞后,下面是我的 drawRect 代码。请帮我找出我哪里出错了
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *mytouch=[[touches allObjects] objectAtIndex:0];
m_previousPoint2 = m_previousPoint1;
m_previousPoint1 = [mytouch previousLocationInView:self];
m_currentPoint = [mytouch locationInView:self];
CGPoint mid1 = midPoint(m_previousPoint1, m_previousPoint2);
CGPoint mid2 = midPoint(m_currentPoint, m_previousPoint1);
testpath = CGPathCreateMutable();
CGPathMoveToPoint(testpath, NULL, mid1.x, mid1.y);
CGPathAddQuadCurveToPoint(testpath, NULL, m_previousPoint1.x, m_previousPoint1.y, mid2.x, mid2.y);
CGRect bounds = CGPathGetBoundingBox(testpath);
CGPathRelease(testpath);
CGRect drawBox = bounds;
//Pad our values so the bounding box respects our line width
drawBox.origin.x -= self.lineWidth * 2;
drawBox.origin.y -= self.lineWidth * 2;
drawBox.size.width += self.lineWidth * 4;
drawBox.size.height += self.lineWidth * 4;
CGContextRef context = UIGraphicsGetCurrentContext();
context = CGLayerGetContext(myLayerRef);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
[self setNeedsDisplayInRect:drawBox];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
if(myLayerRef == nil)
{
myLayerRef = CGLayerCreateWithContext(context, self.bounds.size, NULL);
}
[self.layer renderInContext:context];
CGPoint mid1 = midPoint(m_previousPoint1, m_previousPoint2);
CGPoint mid2 = midPoint(m_currentPoint, m_previousPoint1);
CGContextMoveToPoint(context, mid1.x, mid1.y);
CGContextAddQuadCurveToPoint(context, m_previousPoint1.x, m_previousPoint1.y, mid2.x, mid2.y);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, self.lineWidth);
CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);
CGContextSetFlatness(context, 0.1);
CGContextSetAllowsAntialiasing(context, true);
CGContextStrokePath(context);
[super drawRect:rect];
}
根据@borrrden 的以下讨论更新代码
问候 兰 git
最佳答案
在 WWDC 2012 session 中有一个关于这个确切问题的精彩 session 。我认为它被称为 iOS 性能:图形或类似的东西。你一定要看。
总而言之,不要将其存储在路径中。无需保留此路径信息。存储一个单独的上下文(CGLayer 最好)并绘制到其中(就像您向路径添加点,将点添加到上下文 intead)。然后在您的 drawRect 中,只需将该层绘制到当前图形上下文中。还要确保仅在更改的矩形上调用 setNeedsDisplay
,否则您很可能会在高分辨率设备上遇到问题。
关于ios - UIBezierPath 数组渲染问题(如何使用 CGLayerRef 进行优化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11312135/