如何在Swift中旋转核心文本?

时间:2016-01-28 12:33:11

标签: ios swift rotation core-graphics core-text

所以我有以下代码将CGContext旋转到我的文本所在的位置:

var nums: Int = 0
let oNums: [Int] = [3,4,5,6,7,8,9,10,11,12,1,2]

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))
    CGContextSetStrokeColorWithColor(ctx, UIColor.grayColor().CGColor)
    CGContextMoveToPoint(ctx, 72, 0)
    CGContextSetLineWidth(ctx, 3.0)
    CGContextAddLineToPoint(ctx, 42, 0)
    drawText(ctx!, text: getRoman(oNums[nums]), attributes: [NSForegroundColorAttributeName : UIColor.blackColor().CGColor, NSFontAttributeName : UIFont.systemFontOfSize(12)], x: 42, y: 0, align: CGFloat(6.0 * Double(i) * M_PI / 180))
    nums++
}

drawText(_ :)是:

func drawText(context: CGContextRef, text: NSString, attributes: [String: AnyObject], x: CGFloat, y: CGFloat, align: 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
}

getRoman(_ :)是:

func getRoman(numeral: Int) -> String {switch numeral {case 1:return "I"case 2:return "II"case 3:return "III"case 4:return "IV"case 5:return "V"case 6:return "VI"case 7:return "VII"case 8:return "VIII"case 9:return "IX"case 10:return "X"case 11:return "XI"case 12:return "XII"default:return ""}}

问题是,这会打印文本旋转到一个角度(所需的结果将是所有角度都相同的文本(标准文本方向))

有没有办法旋转核心文字?

问候,布兰登

0 个答案:

没有答案