我正在尝试创建一个方法,它将对UILabel起作用,但在CoreText中,这是我想要做的:
div
问题在于,当我运行应用程序时,它会停在下一行而不会抛出异常:
+(void)drawText:(NSString*)textToDraw
inFrame:(CGRect)frameRect
withFont:(NSString *)fontName
andFontColor:(UIColor *)fontColor
andFontSize:(float)fontSize{
CFStringRef fontN = (__bridge CFStringRef)fontName;
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]
initWithString:textToDraw];
CTFontRef helvetica = CTFontCreateWithName(fontN, fontSize, NULL);
[string addAttribute:(id)kCTFontAttributeName
value:(__bridge id)helvetica
range:NSMakeRange(0, [string length])];
[string addAttribute:(id)kCTForegroundColorAttributeName
value:(id)fontColor.CGColor
range:NSMakeRange(0, [string length])];
CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)string);
CGMutablePathRef framePath = CGPathCreateMutable();
CGPathAddRect(framePath, NULL, frameRect);
// Get the frame that will do the rendering.
CFRange currentRange = CFRangeMake(0, 0);
CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
CGPathRelease(framePath);
// Get the graphics context.
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// Put the text matrix into a known state. This ensures
// that no old scaling factors are left in place.
CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);
// Core Text draws from the bottom-left corner up, so flip
// the current transform prior to drawing.
CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2);
CGContextScaleCTM(currentContext, 1.0, -1.0);
// Draw the frame.
CTFrameDraw(frameRef, currentContext);
CGContextScaleCTM(currentContext, 1.0, -1.0);
CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2);
CFRelease(frameRef);
CFRelease(framesetter);
}
更新
我删除了一些不在此帖子中的额外行后解决了崩溃问题。但是我仍然需要一些帮助来调整这个方法来接受行数和换行模式(NSLineBreakByWordWrapping,NSLineBreakByTruncatingTail ..)
答案 0 :(得分:0)
在弄清楚崩溃的原因之后,我在方法的开头添加了下一行:
textToDraw = [self getDisplayedStringInFrame:frameRect.size
andFont:[UIFont fontWithName:fontName size:fontSize]
andString:textToDraw];
并添加了这个额外的方法来处理我感兴趣的女巫的NSLineBreakByTruncatingTail
效果:
+ (NSString *) getDisplayedStringInFrame:(CGSize)size andFont:(UIFont *)font andString:(NSString *)str{
NSString *written = @"";
int i = 0;
int currentWidth = 0;
NSString *nextSetOfString = @"";
while (1)
{
NSRange range;
range.location = i;
range.length = 1;
NSString *nextChar = [str substringWithRange:range];
nextSetOfString = [nextSetOfString stringByAppendingString:nextChar];
CGSize requiredSize = [nextSetOfString sizeWithFont:font constrainedToSize:CGSizeMake(NSIntegerMax, NSIntegerMax)];
currentWidth = requiredSize.width;
if(size.width >= currentWidth && size.height >= requiredSize.height)
{
written = [written stringByAppendingString:nextChar];
}
else
{
break;
}
i++;
}
written = [written substringToIndex:[written length] - 2];
written = [written stringByAppendingString:@".."];
return written;
}