【发布时间】:2022-10-16 05:48:09
【问题描述】:
我正在尝试在 Swift 的 CoreGraphics 中的 UIImageView 中为动态几何软件应用程序绘制一个字符串。我正在使用上下文图形来绘制点和线,但是当我尝试绘制文本字符串(例如,线段的长度)时,我要么没有文本(例如在这两个示例中),要么其他所有内容除了文本字符串之外,我正在绘制的内容已被删除(抱歉,我没有保存该示例)。在后一种情况下,我可以在字符串顶部绘制其他东西,但这也不是很有帮助,因为我只能绘制一个字符串(尝试绘制第二个字符串删除了第一个字符串)。
以下是两次尝试,均未绘制文本字符串:
UIGraphicsBeginImageContext(canvas.frame.size)
canvas.draw(CGRect(x: 0, y: 0, width: canvas.frame.width, height: canvas.frame.height))
let context = UIGraphicsGetCurrentContext()
let text="\(value)"
let font=UIFont(name: "Helvetica", size: 12)!
let text_style=NSMutableParagraphStyle()
text_style.alignment=NSTextAlignment.center
let text_color=UIColor.black
let attributes=[NSAttributedString.Key.font:font, NSAttributedString.Key.paragraphStyle:text_style, NSAttributedString.Key.foregroundColor:text_color]
let text_x=coordinates.x
let text_y=coordinates.y
let text_rect=CGRect(x: text_x, y: text_y, width: 100, height: font.lineHeight)
text.draw(in: text_rect.integral, withAttributes: attributes)
UIGraphicsEndImageContext()
}```
```override func draw(_ canvas: UIImageView, _ isRed: Bool) {
UIGraphicsBeginImageContext(canvas.frame.size)
canvas.draw(CGRect(x: 0, y: 0, width: canvas.frame.width, height: canvas.frame.height))
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512, height: 512))
let img = renderer.image { ctx in
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-Thin", size: 12)!, NSAttributedString.Key.paragraphStyle: paragraphStyle]
let string = "\(value)"
string.draw(with: CGRect(x: coordinates.x, y: coordinates.y, width: 100, height: 16), options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
}
}```
I have also found a page that says something to the effect that it is impossible to draw text in a UIImageView. However, it is hard to believe that a graphics system as mature as core graphics wouldn't allow drawing text.
【问题讨论】:
标签: swift graphics uiimageview drawtext