0

我关注了另一个 StackOverflow 帖子,该帖子解释了如何覆盖 PDFAnnotation 的 draw 方法,以便我可以绘制图片而不是传统的 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

有人知道我如何覆盖 draw 方法以便绘制自定义注释吗?

谢谢你 !

ps:我也尝试按照苹果开发网站上的教程进行操作。

更新 :

现在我可以使用绘制图片CGContextDrawImage但我无法将坐标翻转回原位。当我这样做时,未绘制 mi 图片,并且似乎将它们放在页面之外,但我不确定。

这是我的新代码:

- (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();
}
4

1 回答 1

1

我还尝试按照 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=底部/左侧)。把它作为 OP 的练习。

回转

您的轮换代码错误:

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();
}

在此处输入图像描述

于 2020-08-06T13:52:06.327 回答