Using CGContext to draw a line

I wanted to draw a string using CGContext, and what I have so far:

CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); CGContextSetLineWidth(context, 1.0f); CGContextMoveToPoint(context, 10, 10); CGContextAddLineToPoint(context, 100, 50); CGContextStrokePath(context); 

It always extends from the upper left corner to the upper lower right corner. How to configure the beginning and end of the beginning of this line? How to adjust the line length?

+6
source share
2 answers

These two lines are responsible for the start and end points:

 CGContextMoveToPoint(context, 10, 10); // This sets up the start point CGContextAddLineToPoint(context, 100, 50); // This moves to the end point. 

Using these two points x, y, you can adjust the line. The length of the line depends on the start and end points.

Following psoft's answer, here is a basic sample drawing project , including creating a path and stroking it.

This is explained in more detail with more sample code in the two-dimensional Quartz guide for paths .

+4
source

CoreGraphics == Good times.

Some time has passed since I did something by hand, what I do these days is all that is needed to perform drawing operations. Remember that there is an implicit โ€œcursorโ€ starting with Logo , and you can move it without having to move the drawing operation, but you must specify it. I believe that a good approach (at least for static numbers) is to create the paths that you will need to draw first, and then use the path again and again for things like fill, stroke, shade.

  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 free the path at the end if you want, or save the link for later use.

+7
source

Source: https://habr.com/ru/post/909140/


All Articles