首页 > 解决方案 > 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); 但它会使文本消失!有人知道原因或遇到类似问题吗?谢谢!

标签: drawrectcgcontextpdfkitpdf-annotations

解决方案


我找到了答案,以防有人遇到同样的问题。实际上 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));对我有用。


推荐阅读