使用核心graphics(移动设备)绘制居中文本

我正在使用这个代码:

CGRect screenRect = [[UIScreen mainScreen] bounds]; CGFloat screenWidth = screenRect.size.width; CGFloat screenHeight = screenRect.size.height; NSString * text = @"text"; CGContextSetFillColorWithColor(context, [UIColor colorWithRed:1 green:1 blue:1 alpha:RETICLE_ALPHA].CGColor); [text drawAtPoint:CGPointMake(screenWidth/2, screenHeight/2) withFont: [UIFont systemFontOfSize:22.0]]; 

为iOS创build一个居中的“文本”。

但是我不确定如何编辑上面的代码来真正使中心alignment起作用,因为直到现在文本并没有真正居中。

对不起,对于那种愚蠢的问题,但我没有find一个工作的例子,我是新的使用核心graphics的问题。

您的文本不居中,因为您必须从屏幕大小减去文本宽度,然后你必须除以2.下面我试图纠正你的代码。

 CGRect screenRect = [[UIScreen mainScreen] bounds]; CGFloat screenWidth = screenRect.size.width; CGFloat screenHeight = screenRect.size.height; NSString * text = @"text"; CGFloat minHeight = 40; float widthIs = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, minHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:22.0] } context:nil].size.width; CGContextSetFillColorWithColor(context, [UIColor colorWithRed:1 green:1 blue:1 alpha:1].CGColor); [text drawAtPoint:CGPointMake((screenWidth - widthIs)/2, (screenHeight - minHeight)/2) withFont: [UIFont systemFontOfSize:22.0]];