我想使用Apple的PDFKit框架更改显示的PDF文档的文本和背景颜色,以显示“夜间模式”(黑色背景,浅色前景,就像Adobe Reader中一样)。 我知道PDFPage类有一个drawWithBox:toContext:方法,可以在子类中进行覆盖以添加效果(例如水印,如此WWDC 2017会话所示),但我不知道如何设置颜色属性。 是否有使用PDFKit库或Apple的任何其他低级API(Quartz)的方法来实现这一点?
想要在PDF中设置文本颜色,可以使用以下方法:
-(CGRect)addText:(NSString*)text withFrame:(CGRect)frame font:(NSString*)fontName fontSize:(float)fontSize andColor:(UIColor*)color{
const CGFloat *val = CGColorGetComponents(color.CGColor);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(currentContext, val[0], val[1], val[2], val[3]);
UIFont *font = [UIFont fontWithName:fontName size:fontSize];
CGSize stringSize = [text sizeWithFont:font constrainedToSize:CGSizeMake(pageSize.width - 2*20-2*20, pageSize.height - 2*20 - 2*20) lineBreakMode:NSLineBreakByWordWrapping];
CGRect renderingRect = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);
[text drawInRect:renderingRect withFont:font lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentLeft];
frame = CGRectMake(frame.origin.x, frame.origin.y, textWidth, stringSize.height);
return frame;
}
关于背景颜色,请使用以下内容
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(currentContext, [UIColor blueColor].CGColor );
CGContextFillRect(currentContext, CGRectMake(0, 110.5, pageSize.width, pageSize.height));