0

朋友们,我正在使用 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 的以下讨论更新

问候兰吉特

4

1 回答 1

2

在 WWDC 2012 会议中有一个关于这个确切问题的精彩会议。我认为它被称为 iOS 性能:图形或类似的东西。你绝对应该看。

总结是,不要将它存储在路径中。无需保留此路径信息。存储一个单独的上下文(CGLayer 是最好的)并绘制到其中(就像你在路径中添加点,在上下文中添加点)。然后在您的 drawRect 中,只需将该层绘制到当前图形上下文中。还要确保只调用setNeedsDisplay已更改的矩形,否则您很可能会在高分辨率设备上遇到问题。

于 2012-07-03T14:43:07.820 回答