iMan Biglari iMan Biglari - 4 months ago 29
Swift Question

Rotate Text in Swift

I am trying to draw a few strings in a custom view with swift. I have done the same thing on Android with Java, and here's the result:

Android Sample

With Swift, I get this graphic:

enter image description here

Here's my code:

let π:CGFloat = CGFloat(M_PI)

extension NSString {
func drawWithBasePoint(basePoint: CGPoint, andAngle angle: CGFloat, andAttributes attributes: [String: AnyObject]) {
let textSize: CGSize = self.sizeWithAttributes(attributes)
let context: CGContextRef = UIGraphicsGetCurrentContext()!
let t: CGAffineTransform = CGAffineTransformMakeTranslation(basePoint.x, basePoint.y)
let r: CGAffineTransform = CGAffineTransformMakeRotation(angle)
CGContextConcatCTM(context, t)
CGContextConcatCTM(context, r)
self.drawAtPoint(CGPointMake(textSize.width / 2, -textSize.height / 2), withAttributes: attributes)
CGContextConcatCTM(context, CGAffineTransformInvert(r))
CGContextConcatCTM(context, CGAffineTransformInvert(t))
}
}

override func drawRect(rect: CGRect) {
elements = delegate!.getRotaryElements(self)
let center = CGPoint(x:bounds.width / 2, y: bounds.height / 2)
let sectorSize = 2 * π / CGFloat.init(elements.count)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Center
for i in 0...elements.count - 1 {
let attrs = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Thin", size: 14)!, NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName:(i % 2 == 0 ? UIColor.redColor():primaryColor)]
elements[i].drawWithBasePoint(center, andAngle: CGFloat(i) * sectorSize + (sectorSize / 2), andAttributes: attrs)
}
}


How can I produce the same thing in Swift? I am new to Swift (and iOS for that matter) and would appreciate any hint you can give me.

Answer

Try the code below, and to see if it works.

let π:CGFloat = CGFloat(M_PI)

extension NSString {
    func drawWithBasePoint(basePoint: CGPoint, andAngle angle: CGFloat, andAttributes attributes: [String: AnyObject]) {
        let radius: CGFloat = 100
        let textSize: CGSize = self.sizeWithAttributes(attributes)
        let context: CGContextRef = UIGraphicsGetCurrentContext()!
        let t: CGAffineTransform = CGAffineTransformMakeTranslation(basePoint.x, basePoint.y)
        let r: CGAffineTransform = CGAffineTransformMakeRotation(angle)
        CGContextConcatCTM(context, t)
        CGContextConcatCTM(context, r)
        self.drawAtPoint(CGPointMake(radius-textSize.width/2, -textSize.height/2), withAttributes: attributes)
        CGContextConcatCTM(context, CGAffineTransformInvert(r))
        CGContextConcatCTM(context, CGAffineTransformInvert(t))
    }
}
Comments