Rotating NSString in Swift

2019-09-01 15:40发布

问题:

I'm trying to do something like the attached image.

I thought this page would lead to the answer

http://www.informit.com/articles/article.aspx?p=2149190&seqNum=13

or

Rotating a NSString in drawRect

Drawing rotated text with NSString drawInRect

but converting objC to swift is troublesome. I can easily draw my arrows but getting the NSString to rotate then translate is problematic. It does weird things like drawing off screen, wrong angles, etc.

I've tried this and many variations

  CGContextSaveGState(context)
  CGContextRotateCTM(context, dTheta[i])
  CGContextTranslateCTM(context, -s.sizeWithAttributes(attributes).width / 2.0, -radiusY )
  s.drawAtPoint(CGPoint(x: x + xOffset*0.0 , y: y + yOffset*0.0 ), withAttributes: attributes)
  //s.drawAtPoint(CGPointMake(0, 0), withAttributes: attributes)
  CGContextRestoreGState(context)

回答1:

Think about what you want to do: draw a string some distance from the center of the circle, rotated about the center of the circle. So, it'd be handy to think of the center of the circle as the origin. I'd do the following:

  1. Translate the CTM so that the origin is at the center of the circle.
  2. Rotate to the correct angle.
  3. Draw the string at {d, 0} (where d is the distance from the center where the text should start.