CGContextAddArc counterclockwise instead of clockwise

I had a problem while drawing an arc inside my drawing function inside a subclass of CALayer. The implementation for this drawing function is as follows:

-(void)drawInContext:(CGContextRef)ctx { CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2); CGFloat radius = MIN(center.x, center.y); CGContextBeginPath(ctx); CGContextAddArc(ctx, center.x, center.y, radius, DEG2RAD(0), DEG2RAD(90), YES); CGContextSetStrokeColorWithColor(ctx, [UIColor whiteColor].CGColor); CGContextSetLineWidth(ctx, 5); CGContextDrawPath(ctx, kCGPathStroke); } 

There is nothing revolutionary here, but it is strange that he draws an arc counterclockwise, although I indicated that it will be clockwise. Conversely, when I specify NO for a parameter in a clockwise direction, it draws an arc in a clockwise direction. I did some research on inverted coordinate systems and realized that this could be a problem, but I didn't want to just specify the opposite bool parameter, which I had in mind. Any suggestions on how to fix this?

Thanks!

+6
source share
1 answer

This is really due to the inverted coordinate system UIKit and Quartz. From the docs for CGContext :

The parameter clockwise determines the direction in which the arc is created; the actual direction of the final path depends on the current graphic context transformation matrix. For example, on iOS, UIView flips the Y coordinate, scaling the Y value by -1. In an inverted coordinate system, specifying an arc in a clockwise direction results in an arc counterclockwise after applying the transformation.

You can facilitate this in your code by using the transformation matrix to flip your context:

 CGContextTranslateCTM(ctx, 0.0, self.bounds.size.height); CGContextScaleCTM(ctx, 1.0, -1.0); 

You probably want to flip it when you're done with the ie drawing

 CGContextSaveGState(ctx); CGContextTranslateCTM(ctx, 0.0, self.bounds.size.height); CGContextScaleCTM(ctx, 1.0, -1.0); // Draw... CGContextRestoreGState(ctx); 
+7
source

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


All Articles