我遵循了另一篇StackOverflow文章,解释了如何重写PDFAnnotation的绘图方法,这样我就可以画一幅图片而不是传统的PDFAnnotation了。
但遗憾的是,我未能做到这一点,而在我的pdf上绘制的注释仍然是一个常规注释。
这是我使用的代码:
@implementation PDFImageAnnotation { UIImage * _picture;
CGRect _bounds;};
-(instancetype)initWithPicture:(nonnull UIImage *)picture bounds:(CGRect) bounds{
self = [super initWithBounds:bounds
forType:PDFAnnotationSubtypeWidget
withProperties:nil];
if(self){
_picture = picture;
_bounds = bounds;
}
return self;
}
- (void)drawWithBox:(PDFDisplayBox) box
inContext:(CGContextRef)context {
[super drawWithBox:box inContext:context];
[_picture drawInRect:_bounds];
CGContextRestoreGState(context);
UIGraphicsPushContext(context);
};
@end有人知道我怎样才能覆盖这个绘制方法,这样我就可以画一个自定义注释了吗?
谢谢!
ps:我还试着遵循苹果开发网站上的教程。
更新:
现在,我可以使用CGContextDrawImage绘制图片,但无法将坐标翻转回原处。当我这样做的时候,我的图片就不会被画出来,而且看起来它们被放到了页面之外,但我不确定。
这是我的新代码:
- (void)drawWithBox:(PDFDisplayBox) box
inContext:(CGContextRef)context {
[super drawWithBox:box inContext:context];
UIGraphicsPushContext(context);
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0.0, _pdfView.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, _bounds, _picture.CGImage);
CGContextRestoreGState(context);
UIGraphicsPopContext();
}发布于 2020-08-06 13:52:06
我还试着在Apple网站上学习这个教程。
哪个?
因为两者都包括UIGraphicsPushContext(context)和CGContextSaveGState(context)调用,但是您的代码没有。不要盲目地复制和粘贴示例,试着理解它们。看看这两个电话是怎么回事。
固定代码:
- (void)drawWithBox:(PDFDisplayBox) box
inContext:(CGContextRef)context {
[super drawWithBox:box inContext:context];
UIGraphicsPushContext(context);
CGContextSaveGState(context);
[_picture drawInRect:_bounds];
CGContextRestoreGState(context);
UIGraphicsPopContext();
}

图像用CGRectMake(20, 20, 100, 100)绘制。它是颠倒的,因为PDFPage坐标是翻转的(0, 0 =底部/左)。把它当作操作练习。
旋转
您的轮换代码是错误的:
CGContextTranslateCTM(context, 0.0, _pdfView.bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, _bounds, _picture.CGImage);它基于_pdfView边界,但它应该基于图像边界(_bounds)。以下是正确的答案:
- (void)drawWithBox:(PDFDisplayBox) box
inContext:(CGContextRef)context {
[super drawWithBox:box inContext:context];
UIGraphicsPushContext(context);
CGContextSaveGState(context);
CGContextTranslateCTM(context, _bounds.origin.x, _bounds.origin.y + _bounds.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
[_picture drawInRect:CGRectMake(0, 0, _bounds.size.width, _bounds.size.height)];
CGContextRestoreGState(context);
UIGraphicsPopContext();
}

https://stackoverflow.com/questions/63283248
复制相似问题