2016-02-13 74 views
3

我正在嘗試使用CoreGraphics製作模擬時鐘。如何用Swift旋轉核心文本?

我的問題是,我不知道如何旋轉數字的文字。

代碼的一般過程如下:

首先我旋轉的範圍內,然後,如果適用的話我繪製的數;重複。

完整的遊樂場

import UIKit 
import Foundation 
import XCPlayground 

class ClockFace: UIView { 
    func drawText(context: CGContextRef, text: NSString, attributes: [String: AnyObject], x: CGFloat, y: CGFloat) -> CGSize { 
     CGContextTranslateCTM(context, 0, 0) 
     CGContextScaleCTM(context, 1, -1) 
     let font = attributes[NSFontAttributeName] as! UIFont 
     let attributedString = NSAttributedString(string: text as String, attributes: attributes) 

     let textSize = text.sizeWithAttributes(attributes) 

     let textPath = CGPathCreateWithRect(CGRect(x: -x, y: y + font.descender, width: ceil(textSize.width), height: ceil(textSize.height)), nil) 
     let frameSetter = CTFramesetterCreateWithAttributedString(attributedString) 
     let frame  = CTFramesetterCreateFrame(frameSetter, CFRange(location: 0, length: attributedString.length), textPath, nil) 

     CTFrameDraw(frame, context) 

     return textSize 
    } 

    override func drawRect(rect: CGRect) { 
     let ctx: CGContext? = UIGraphicsGetCurrentContext() 
     var nums: Int = 0 
     for i in 0..<60 { 
      CGContextSaveGState(ctx) 
      CGContextTranslateCTM(ctx, rect.width/2, rect.height/2) 
      CGContextRotateCTM(ctx, CGFloat(6.0 * Double(i) * M_PI/180)) 
      CGContextMoveToPoint(ctx, 72, 0) 
      if (i % 5 == 0) { 
       nums++ 
       drawText(ctx!, text: "\(nums)", attributes: [NSForegroundColorAttributeName : UIColor.blackColor().CGColor, NSFontAttributeName : UIFont.systemFontOfSize(12)], x: 42, y: 0) 
      } 
      CGContextRestoreGState(ctx) 
     } 

    } 
} 
let myView = ClockFace(frame: CGRectMake(0, 0, 150, 150)) 
myView.backgroundColor = .lightGrayColor() 
XCPShowView("", view: myView) 

因此我的問題,如何與斯威夫特一個旋轉核心文本?

回答

1

您可以通過CGContextSetTextMatrix()實現CGAffineTransform來旋轉文本。例如:

... 
let frame = CTFramesetterCreateFrame(frameSetter, CFRange(location: 0, length: attributedString.length), textPath, nil) 
CGContextSetTextMatrix(context, CGAffineTransformMakeRotation(CGFloat(M_PI))) 
CTFrameDraw(frame, context) 
+0

context.textMatrix = CGAffineTransform.init(rotationAngle:CGFloat.pi) ---(CGContextSetTextMatrix已被刪除,設置上下文的文本矩陣屬性) – Robby