我正在使用 CGContext 渲染 NSAttributedString,但是当它渲染时,文本是颠倒的:(
这是我想到的:
override func draw(with box: PDFDisplayBox, in context: CGContext) {
UIGraphicsPushContext(context)
context.saveGState()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes = [
NSAttributedString.Key.paragraphStyle: paragraphStyle,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 80.0),
NSAttributedString.Key.foregroundColor: UIColor.red
]
NSAttributedString(string: self.widgetStringValue!, attributes: attributes).draw(in: self.bounds)
context.restoreGState()
UIGraphicsPopContext()
}
我尝试添加这个:
context.translateBy(x: 0.0, y: bounds.height)
context.scaleBy(x: 1.0, y: -1.0)
但是文本根本没有出现在我的屏幕上:(
我做错了什么?
更新
根据要求,这是我的完整 TextAnnotation 类:
class TextAnnotation: PDFAnnotation {
var currentText: String?
override init(bounds: CGRect, forType annotationType: PDFAnnotationSubtype, withProperties properties: [AnyHashable : Any]?) {
super.init(bounds: bounds, forType: annotationType, withProperties: properties)
self.widgetFieldType = PDFAnnotationWidgetSubtype(rawValue: PDFAnnotationWidgetSubtype.text.rawValue)
self.font = UIFont.systemFont(ofSize: 80)
self.isMultiline = true
self.widgetStringValue = "Text Here"
self.currentText = self.widgetStringValue!
}
override func draw(with box: PDFDisplayBox, in context: CGContext) {
UIGraphicsPushContext(context)
context.saveGState()
let pageBounds = bounds
context.translateBy(x: 0, y: pageBounds.height)
context.scaleBy(x: 1, y: -1)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attributes: [NSAttributedString.Key: Any] = [
.paragraphStyle: paragraphStyle,
.font: UIFont.systemFont(ofSize: 80),
.foregroundColor: UIColor.red
]
widgetStringValue!.draw(in: pageBounds, withAttributes: attributes)
context.restoreGState()
UIGraphicsPopContext()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
最佳答案
就我而言,我正在对 PDFAnnotation 进行子类化。关键是在我的绘制方法中使用正确的 y 值(这是一个很难弄清楚的过程)来进行 translateBy 调用:
override func draw(with box: PDFDisplayBox, in context: CGContext) {
let text = NSString(string: "Hello!")
UIGraphicsPushContext(context)
context.saveGState()
context.translateBy(x: 0, y: bounds.height + (2 * bounds.minY))
context.scaleBy(x: 1, y: -1.0)
text.draw(in: bounds.offsetBy(dx: 2, dy: 0), withAttributes: attributes)
context.restoreGState()
UIGraphicsPopContext()
}
关于ios - CGContext 颠倒呈现文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57275769/