【发布时间】:2018-05-30 12:13:37
【问题描述】:
我正在做一个项目,我必须在 UIView 中绘制文本字符串。问题不是绘制字符串,而是旋转它们。我希望将文本绘制在与红线相同的角度上方。查看下图:
插图示例:
这是代码...(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)
}
}
【问题讨论】:
-
你试过
CGAffineTransform(rotationAngle: -CGFloat.pi / 2)吗? -
您问题的标题措辞不当。字符串和属性字符串没有轮换。它们是文本的表示。最好问“如何绘制围绕特定点旋转的 NSAttributedString?”
-
感谢@DuncanC 的建设性反馈,你是对的。
-
嗨@ArnabHore。感谢您的答复。我已经尝试过了,但它会围绕每个角色各自的锚点旋转。我想将字符串作为一个整体旋转。
标签: ios swift uiview nsattributedstring uigraphicscontext