gpt4 book ai didi

ios - CGContext 颠倒呈现文本

转载 作者:行者123 更新时间:2023-11-28 07:23:42 25 4
gpt4 key购买 nike

我正在用 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。关键是在我的绘制方法中为 translateBy 调用使用正确的 y 值(很难弄清楚):

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com