2016-02-13 97 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