Using CGContext to draw line

后端 未结 2 1998
猫巷女王i
猫巷女王i 2021-01-12 06:02

I wanted to draw a line using CGContext and what I have so far is:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(con         


        
2条回答
  •  终归单人心
    2021-01-12 06:16

    CoreGraphics == Good Times.

    It's been a while since I did anything freehand as it were, what I do these days is to build everything ahead of drawing operations. Remember that there is an implicit 'cursor', from the days of Logo, and you can move it without making the move a drawing operation, but you have to specify it. I think a good approach (at least for static figures) is to create those paths you will have to draw first, then using the path over and over for things like fill, stroke, shading.

       CGColorRef fillColor = // yadda
       CGColorRef strokeColor = // yadda
    
       const CGFloat radius = 5.0;
    
       // Create the path first - rounded rectangle
       CGMutablePathRef path = CGPathCreateMutable();
       CGPathMoveToPoint(path, NULL, 100.0 - radius, 10.0);
       CGPathAddLineToPoint(path, NULL, 10.0 + radius, 10.0);
       CGPathAddArcToPoint(path, NULL, 10.0, 10.0, 10.0, 10.0 + radius, radius);
       CGPathAddLineToPoint(path, NULL, 10.0, 100.0 - radius);
       CGPathAddArcToPoint(path, NULL, 10.0, 100.0, 10.0 + radius, 100.0, radius);
       CGPathAddLineToPoint(path, NULL, 100.0 - radius, 100.0);
       CGPathAddArcToPoint(path, NULL, 100.0, 100.0, 100.0, 100.0 - radius, radius);
       CGPathAddLineToPoint(path, NULL, 100.0, 10.0 + radius);
       CGPathAddArcToPoint(path, NULL, 100.0, 10.0, 100.0 - radius, 10.0, radius);
       CGPathCloseSubpath(path);
    
       // Then use it in your draw commands
       CGContextSetStrokeColor(context, CGColorGetComponents(strokeColor));
       CGContextSetFillColor(context, CGColorGetComponents(fillColor));
       CGContextSetLineJoin(context, kCGLineJoinMiter);
       CGContextSetLineWidth(context, strokeWidth);
    
       CGContextAddPath(context, path);
       CGContextDrawPath(context, kCGPathFillStroke);
       CGPathRelease(path); 
    

    Etc. You can release the path at the end if you want, or keep the reference around for use later on.

提交回复
热议问题