如何绘制围绕特定点旋转的NSAttributedString?

时间:2018-05-30 12:13:37

标签: ios swift uiview nsattributedstring uigraphicscontext

我正在研究一个项目,我必须在UIView中绘制文本字符串。问题不是绘制字符串,而是旋转它们。我希望文本在上面绘制并与红线成相同的角度。请查看下图:

插图示例:

enter image description here

这是代码......(PS。删除所有不相关的代码)

class DrawView: UIView {

    override func draw(_ rect: CGRect) {

        let context = UIGraphicsGetCurrentContext()!

        // Adding a line here.
        context.move(to: CGPoint(x: 290, y: 650))
        context.addLine(to: CGPoint(x: 530, y: 530))
        context.strokePath()

        // Flipping the coordinate system
        context.textMatrix = .identity
        context.translateBy(x: 0, y: bounds.size.height)
        context.scaleBy(x: 1.0, y: -1.0)

        // Creating the text path.
        let path = CGMutablePath()
        // "x" and "y" equals the staring point of the line. "width" equals the length of the line.
        path.addRect(CGRect(x: 290, y: 650, width: 268, height: 30))

        // I have tried rotating with the method below, but it rotates with the anchor point at (0, 0) in the UIView.
        //context.rotate(by: 0.4636) //   0.4636 equals the angle of the red line in radians.

        // Setting the text justification to center.
        let justification = NSMutableParagraphStyle()
        justification.alignment = NSTextAlignment.center

        // Creating the attribute.
        let attribute = [NSAttributedStringKey.font:  UIFont(name: "Arial", size: 22.0)!,
                         NSAttributedStringKey.foregroundColor: UIColor.black,
                         NSAttributedStringKey.paragraphStyle: justification] as [NSAttributedStringKey : Any]?

        // Creating the string and setting up the frame.
        let attrString = NSAttributedString(string: "12032.00", attributes: attribute)
        let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString)
        let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attrString.length), path, nil)

        CTFrameDraw(frame, context)
    }
}

2 个答案:

答案 0 :(得分:2)

感谢大家,我终于想通了,非常感谢@Grimxn。这就是我解决它的方法:

// Set attributes.
let attribute = [NSAttributedStringKey.font:  UIFont(name: "Courier", size: 22.0)!] as [NSAttributedStringKey : Any]?
// Save current context.
context.saveGState()
// Move orgin.
context.translateBy(x: 290, y: 650)
// Rotate the coordinate system.
context.rotate(by: -0.4636)
// Create a string.
let str = "12300.10"
// Draw string.
str.draw(at: CGPoint(x: 0, y: 0), withAttributes: attribute)
// Restore to saved context.
context.restoreGState()

答案 1 :(得分:1)

旋转总是在当前的0点进行。如果要围绕不同的中心旋转,则必须移动矩阵以将所需的旋转点放在原点上,旋转并向后移动。