Ios 在PDF上绘制的图像是颠倒的

Ios 在PDF上绘制的图像是颠倒的,ios,pdf,uiimage,Ios,Pdf,Uiimage,我试图在现有的PDF(显示在屏幕上)上绘制图像。最终目标是在任何地方签署pdf 代码(基本)的工作原理如下: 用户单击要绘制图像的位置 进行PDF编辑,最终PDF显示在屏幕上 然而,问题是我的形象似乎颠倒了。在使用PDF时,我了解到必须翻转上下文才能渲染,这可能是相关的 - (void)editPDFWithName:(NSString*)pdfName { // grab reference to bundled PDF CGPDFDocumentRef pdf = CGPDFDocum

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

代码(基本)的工作原理如下:

  • 用户单击要绘制图像的位置
  • 进行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];
-(void)editPDFWithName:(NSString*)pdfName
{
//抓取对捆绑PDF的参考
CGPDFDocumentRef pdf=CGPDFDocumentCreateWithURL((CFURLRef)[[NSBundle mainBundle]URLForResource:pdfName with extension:@“pdf]”);
const size\u t numberOfPages=CGPDFDocumentGetNumberOfPages(pdf);
//开始PDF上下文
NSMutableData*数据=[NSMutableData];
UIGraphicsBeginPDFContextToData(数据,CGRectZero,nil);
//在PDF页面上循环以呈现它

对于(size_t page=1;page嗯,我终于找到了解决方案:

  • 使用
    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)];