1
我想用swift在自定義視圖中繪製幾個字符串。我也做了同樣的事情在Android與Java,和這裏的結果:在Swift中旋轉文本
與SWIFT,我得到這個圖形:
這裏是我的代碼:
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的新手),希望你能給我提供任何提示。
你的'drawWithBasePint'方法是什麼樣的?它不是來自iOS SDK。 – Fujia
@富佳對不起。我忘記了包括它。 –