如何在iPhone上使用Quartz显示文本?
时间:2020-03-06 14:49:15 来源:igfitidea点击:
我一直在尝试使用Quartz上下文显示文本,但是无论我尝试了什么,我都没有运气让文本显示出来(尽管我能够显示各种其他Quartz对象)。有人知道我可能做错了吗?
例子:
-(void)drawRect:(CGRect)rect { // Drawing code CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSelectFont(context, "Arial", 24, kCGEncodingFontSpecific); CGContextSetTextPosition(context,80,80); CGContextShowText(context, "hello", 6); //not even this works CGContextShowTextAtPoint(context, 1,1, "hello", 6); }
解决方案
这是我正在使用的代码片段。
UIColor *mainTextColor = [UIColor whiteColor]; [mainTextColor set]; drawTextLjust(@"Sample Text", 8, 50, 185, 18, 16);
和:
static void drawTextLjust(NSString* text, CGFloat y, CGFloat left, CGFloat right, int maxFontSize, int minFontSize) { CGPoint point = CGPointMake(left, y); UIFont *font = [UIFont systemFontOfSize:maxFontSize]; [text drawAtPoint:point forWidth:right - left withFont:font minFontSize:minFontSize actualFontSize:NULL lineBreakMode:UILineBreakModeTailTruncation baselineAdjustment:UIBaselineAdjustmentAlignBaselines]; }
好,我知道了。首先,将编码模式更改为kCGEncodingMacRoman。其次,在其下面插入以下行:
CGContextSetTextMatrix(canvas, CGAffineTransformMake(1, 0, 0, -1, 0, 0));
这将设置文本的转换矩阵,以便正确绘制它。如果我们不输入该行,则文本将上下颠倒并排回到前面。不知道为什么这不是默认值。最后,请确保设置正确的填充色。如果我们忘记将背景颜色更改为文本颜色,而最终得到的是白色文本,这是一个容易犯的错误。