2016-07-29 98 views
1

我想用swift在自定義視圖中繪製幾個字符串。我也做了同樣的事情在Android與Java,和這裏的結果:在Swift中旋轉文本

Android Sample

與SWIFT,我得到這個圖形:

enter image description here

這裏是我的代碼:

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) 
     } 
    } 

如何在Swift中生成同樣的東西?我是Swift(和iOS的新手),希望你能給我提供任何提示。

+0

你的'drawWithBasePint'方法是什麼樣的?它不是來自iOS SDK。 – Fujia

+0

@富佳對不起。我忘記了包括它。 –

回答

2

嘗試下面的代碼,看它是否有效。

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)) 
    } 
}