我正在使用下面的代码将文字写入pdf。这是非常标准的东西,使用属性来设置文本样式。
使用属性有效,但我需要能够缩小文本以适应可用的框架,类似于UILabel。似乎没有任何类型的最小字体大小设置,这可能是有意义的,因为属性文本可以在字体和大小上变化。
那么,当输出到 pdf 时,有没有办法衡量文本的建议大小以查看它是否适合框架,从而允许我减少我的手动字体大小属性?
-(void)drawText:(NSString*)text inFrame:(CGRect)frameRect withAttributes:(NSDictionary*)attributes
{
CFStringRef stringRef = (__bridge CFStringRef)text;
CFDictionaryRef attributeRef = (__bridge CFDictionaryRef)attributes;
CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, stringRef, attributeRef);
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);
CFRange currentRange = CFRangeMake(0, 0);
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
CGPathRelease(framePath);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
CGFloat offset = (frameRect.origin.y*2)+frameRect.size.height;
CGContextTranslateCTM(currentContext, 0, offset);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CTFrameDraw(frameRef, currentContext);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGContextTranslateCTM(currentContext, 0, -offset);
CFRelease(frameRef);
CFRelease(framesetter);
CFRelease(currentText);
}