【问题标题】:Drawn image over PDF is upside-down在 PDF 上绘制的图像是颠倒的
【发布时间】:2016-05-29 04:32:48
【问题描述】:

我正在尝试在现有 PDF(显示在屏幕上)上绘制图像。最终目标是在任何地方签署 pdf。

My sample code is here on Github

代码(基本)是这样工作的:

  • 用户点击他想要绘制图像的位置
  • 进行 PDF 编辑,最终的 PDF 出现在屏幕上

但问题是我的图像看起来是颠倒的。在使用 PDF 时,我了解到您必须翻转上下文才能呈现,这可能是相关的。

- (void)editPDFWithName:(NSString*)pdfName
{
// grab reference to bundled PDF
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)[[NSBundle mainBundle] URLForResource:pdfName withExtension:@"pdf"]);

const size_t numberOfPages = CGPDFDocumentGetNumberOfPages(pdf);

// Begin PDF context
NSMutableData* data = [NSMutableData data];
UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);

// loop over PDF pages to render it
for(size_t page = 1; page <= numberOfPages; page++)
{
    //  Get the current page and page frame
    CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf, page);
    const CGRect pageFrame = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);

    UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);

    //  Draw the page (flipped)
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);

    // Y axis is negative in order to render PDF (mandatory)
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -pageFrame.size.height);
    CGContextDrawPDFPage(ctx, pdfPage);
    CGContextRestoreGState(ctx);

    if(page == [self getCurrentPage])
    {
        // 0.75f factor to convert pixel/points
        CGContextDrawImage(ctx, CGRectMake(self.xTouchCoord*0.75f, self.yTouchCoord*0.75f, self.logo.size.width, self.logo.size.height), self.logo.CGImage);
    }

}
UIGraphicsEndPDFContext();

CGPDFDocumentRelease(pdf);
pdf = nil;

//  Save PDF
[self savePDF:data];

}

I tried multiple ways to flip image as suggested on this post

但图像仍然翻转。

我注意到的一件事是如果我在图像上使用drawAtPoint方法,它看起来没有翻转但没有出现在指定位置,就像有一个偏移量(see other post here)

有人可以提出任何想法吗?我赌的是保存和恢复上下文方法,但不能让它工作。

【问题讨论】:

    标签: ios pdf uiimage


    【解决方案1】:

    好吧,我终于找到了解决方案:

    • 使用drawInRect而不是CGContextDrawImage
    • 为了更好的精度,不要忘记将坐标的宽度和高度减去一半来调整中心:

          // 0.75f factor to convert pixel/points
          [self.logo drawInRect:CGRectMake(self.xTouchCoord*0.75f - self.logo.size.width/2, self.yTouchCoord*0.75f - self.logo.size.width/2, self.logo.size.width, self.logo.size.height)];
      

    【讨论】:

      猜你喜欢
      • 2012-02-19
      • 2018-06-21
      • 1970-01-01
      • 2022-08-05
      • 2015-12-26
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多