drawrect - iOS:文本在 drawRect 函数中颠倒
问题描述
我正在使用PDFKit
并创建一个子类PDFAnnotation
,我想在创建自由文本注释时设置我的自定义填充,所以我尝试覆盖 drawRect 函数,如下所示
- (void)drawWithBox:(PDFDisplayBox)box inContext:(CGContextRef)context {
UIGraphicsPushContext(context);
CGContextSaveGState(context);
NSAttributedString * mystring = [[NSAttributedString alloc] initWithString:self.contents attributes:@{
NSFontAttributeName: self.font,
NSForegroundColorAttributeName: UIColor.blackColor }];
[mystring drawInRect:CGRectMake(self.bounds.origin.x + 10, self.bounds.origin.y + 10, self.bounds.size.width-20, self.bounds.size.height-20)];
CGContextRestoreGState(context);
UIGraphicsPopContext();
}
填充效果很好,但文字是颠倒的。
我尝试基于此链接https://forums.developer.apple.com/thread/103683添加上下文翻转代码
CGContextTranslateCTM(context, 0.0, self.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
行后CGContextSaveGState(context);
但它会使文本消失!有人知道原因或遇到类似问题吗?谢谢!
解决方案
我找到了答案,以防有人遇到同样的问题。实际上 CGContextTransform 是基于页面坐标系的,所以当你使用变换时CGContextScaleCTM(context, 1.0, -1.0);
,上下文在页面范围之外。我们需要得到的是X1 = X2; Y1 + Y2 = 2 * (self.bounds.origin.y + self.bounds.size.height / 2)
,所以应用转换CGContextConcatCTM(context, CGAffineTransformMake(1, 0, 0, -1, 0.0, 2 * self.bounds.origin.y + self.bounds.size.height));
对我有用。
推荐阅读
- css - 没有使用 scss intelliSense 和 scss 扩展从 vscode 获得 scss 建议
- linux - 如何在 Oracle Linux 8 中安装调试工具?
- html - 为什么我的 react-boostrap 按钮的 CSS 不起作用?
- php - 如何在 Controller Laravel 中记录每个功能
- indexing - 为什么索引 HashMap 不返回引用?
- google-app-engine - GAE - 如何在 quarkus java11 应用程序中配置从 Google App Engine 访问 Cloud SQL?
- curl - curl 默认应该使用 tls1.2 而不是 tls1.3
- python - 通过函数调用字典中键的值
- python - 如果未提供名称字段,则显示错误消息的方法
- php - 权限用户和管理员 yii2