在iOS7中,不推荐使用CGContextSelectFont。弃用消息说我必须使用Core Text,但我不知道这段代码的确切等价:
CGContextSelectFont(context, "Helvetica", kBarLabelSize, kCGEncodingMacRoman);
CGContextSetTextDrawingMode(context, kCGTextFill);
CGContextSetRGBFillColor(context, 0, 0, 0, 1.0);
CGContextSetTextMatrix (context, CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0));
CGContextShowTextAtPoint(context, barX, barY, [@"Some text" cStringUsingEncoding:NSUTF8StringEncoding], [barValue length]);
我已经能够使用以下代码创建字体:
CFMutableAttributedStringRef attrStr = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica"), kBarLabelSize, NULL);
CFAttributedStringSetAttribute(attrStr, CFRangeMake(0, CFAttributedStringGetLength(attrStr)), kCTFontAttributeName, font);
但现在我可以用这种字体“画”一个文字到上下文中吗?
答案 0 :(得分:24)
从我的代码中我可以理解,完全相同的是:
CGContextSetTextDrawingMode(context, kCGTextFill); // This is the default
[[UIColor blackColor] setFill]; // This is the default
[@"Some text" drawAtPoint:CGPointMake(barX, barY)
withAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Helvetica"
size:kBarLabelSize]
}];
请注意,您对CGContextSetTextDrawingMode
和CGContextSetRGBFillColor
的调用会将值设置为默认值。使用像这样的UIKit绘图时,不需要调用CGContextSetTextMatrix
。
然而,我不知道[barValue length]
是什么。我假设您只是错误地将其用于@"Some text"
的长度。 (length
不是您需要的字节数。您可能想要的是[barValue lengthOfBytesUsingEncoding:NSUTF8StringEncoding]
)。
请注意,UIKit字符串绘制(此处显示)包装了Core Text。
答案 1 :(得分:10)
我发现,至少在我的情况下,新NSString.drawAtPoint接口的问题在于它可能颠倒过来,具体取决于您使用上下文的方式。
另一种方法是使用Core Text方法,特别是CTLine接口:
NSDictionary *attribs = @{NSFontAttributeName:[UIFont fontWithName:@"Helvetica" size:14.0]};
NSAttributedString *fontStr = [[NSAttributedString alloc] initWithString:@"some text" attributes:attribs];
CTLineRef displayLine = CTLineCreateWithAttributedString( (__bridge CFAttributedStringRef)fontStr );
CGContextSetTextPosition( ctx, xPosition, yPosition );
CTLineDraw( displayLine, ctx );
CFRelease( displayLine );
答案 2 :(得分:0)
您可能可以使用以下内容替换它。
CGContextSetFont
CGContextSetFontSize