如何在Core Text Programming中设置字体大小和名称?

时间:2012-09-25 06:58:35

标签: iphone objective-c ios core-text

以下是我的代码崩溃

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);

我想设置字体请帮帮我谢谢。

+(void)drawText:(NSString*)textToDraw inFrame:(CGRect)frameRect
{

    //  CFStringRef stringRef = (__bridge CFStringRef)textToDraw;
    //  Prepare the text using a Core Text Framesetter

    NSAttributedString *stringRef=[[[NSAttributedString alloc]initWithString:textToDraw attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:12.0],(NSString*)kCTFontAttributeName, nil]]autorelease];

    CFAttributedStringRef currentText =(__bridge CFAttributedStringRef)stringRef;
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);// at this Line it giving me EXC_BAD_ACCESS

    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);
    CGContextTranslateCTM(currentContext, 0, frameRect.origin.y*2);
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    CTFrameDraw(frameRef, currentContext);
    CGContextScaleCTM(currentContext, 1.0, -1.0);
    CGContextTranslateCTM(currentContext, 0, (-1)*frameRect.origin.y*2);
    CFRelease(frameRef);
    //CFRelease(currentText);
    CFRelease(framesetter);
    //CFRelease(stringRef);
}

1 个答案:

答案 0 :(得分:7)

试试这个

CTFontRef font = CTFontCreateWithName((CFStringRef)@"Helvetica", 16.0f, nil);
CFAttributedStringSetAttribute(currentText,CFRangeMake(0, _stringLength-1),kCTFontAttributeName,font);