【发布时间】: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