2016-02-13 3 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) 

Поэтому мой вопрос, как же один поворот основного текста с Swift?

ответ

1

Вы можете установить CGAffineTransform через CGContextSetTextMatrix(), чтобы повернуть тексты. Пример:

... 
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

Смежные вопросы