【问题标题】:drawInRect doesn't work with PDFdrawInRect 不适用于 PDF
【发布时间】:2016-02-08 11:23:34
【问题描述】:

我正在更新一个旧应用程序,但我无法让 drawInRect 在 PDF 上下文中工作。

我用 CGContextShowTextAtPoint 替换了已弃用的函数 CGContextShowTextAtPoint(参见下面的代码),但它没有写入任何文本。

我哪里错了?

这是我的代码:

-(NSMutableData *) writeToPDF {

CGRect          pageRect;

pageRect = CGRectMake(0.0f, 0.0f, 612, 850);

NSMutableData *pdfData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)pdfData);

CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, &pageRect, NULL);

CGContextSetTextDrawingMode (pdfContext, kCGTextFill);

// Page 1

CGContextBeginPage(pdfContext, &pageRect);
CGContextSetRGBStrokeColor(pdfContext, 0, 0, 0, 1);

CGAffineTransform transf = CGAffineTransformMake(1, 0, 0, -1, 0, pageRect.size.height);
CGContextConcatCTM(pdfContext, transf);

// Line - OK

CGContextMoveToPoint(pdfContext,0,0);
CGContextAddLineToPoint(pdfContext,pageRect.size.width,pageRect.size.height);
CGContextDrawPath(pdfContext, kCGPathStroke);

CGContextSetTextDrawingMode (pdfContext, kCGTextFill);

CGAffineTransform myTextTransform = CGAffineTransformMake(1,0,0,-1,0,0);
CGContextSetTextMatrix(pdfContext, myTextTransform);

// Text - Old working code to replace because CGContextSelectFont and CGContextShowTextAtPoint are deprecated

CGContextSelectFont(pdfContext, "Helvetica", 20, kCGEncodingMacRoman);
CGContextShowTextAtPoint(pdfContext, 50, 50, [@"Hello" UTF8String], [@"Hello" length]);

// Text - Replacing code that doesn't work 

NSDictionary *attrs = @{ NSForegroundColorAttributeName : [UIColor blackColor],
                         NSFontAttributeName : [UIFont systemFontOfSize:20]
                       };


[@"Hello2" drawInRect:CGRectMake(50, 100, 100, 100) withAttributes:attrs];

CGContextDrawPath(pdfContext, kCGPathStroke);

CGContextEndPage(pdfContext);

//

CGPDFContextClose(pdfContext);
CGContextRelease(pdfContext);

CGDataConsumerRelease(dataConsumer);

return pdfData;
}

【问题讨论】:

  • 我无法立即测试您的代码 - 但您是否在某处设置了当前图形上下文? drawInRect 使用当前的图形上下文,我没有看到您在任何地方将 PDF 上下文设置为当前。查看 UIGraphicsPushContext 将您的 PDF 上下文设置为当前。
  • 谢谢,这就是解决方案。你拯救了我的一天。我想知道 drawInRect 是如何知道当前上下文的,但我完全错过了 UIGraphicsPushContext。
  • 我会写一个简短的答案,以便您批准,其他人也可以稍后看到答案。

标签: ios pdf quartz-graphics quartz-2d


【解决方案1】:

与您使用的其他函数不同,drawInRect 不采用图形上下文。这意味着它使用当前的图形上下文,您必须在调用之前确保您的 PDF 上下文是最新的。

使用 UIGraphicsPushContext 函数可以使您的图形上下文成为最新的。完成后不要忘记再次弹出图形上下文。

【讨论】:

    猜你喜欢
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 2015-08-05
    • 2016-09-14
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多