Как нарисовать NSAttributedString повернутой вокруг определенной точки? - PullRequest
0 голосов
/ 30 мая 2018

Я работаю над проектом, где мне нужно рисовать строки текста в 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 голосов
/ 31 мая 2018

Спасибо всем вам, я наконец понял это, большое спасибо @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()
0 голосов
/ 30 мая 2018

Вращение всегда выполняется в текущей точке 0,0.Если вы хотите вращаться вокруг другого центра, вам нужно сместить матрицу, чтобы поместить желаемую точку вращения на начало координат, повернуть и сдвинуть назад.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...