我一直在尝试使用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));

这将设置文本的转换矩阵,以便正确绘制。如果您不放入该行,您的文本将颠倒并返回到前面。不知道为什么这不是默认值。最后,确保您设置了正确的填充颜色。如果您忘记从背景颜色更改为文本颜色并最终使用白色白色文本,则很容易犯错误。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top