我正在使用此代码:
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创建一个居中的“文本”。
但是我不确定如何编辑上面的代码来真正使中心对齐工作,因为到目前为止,文本并没有真正集中。
对不起,对于那种愚蠢的问题,但我没有找到问题的实例,我是使用Core 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]];