使用核心图形绘制居中文本(移动设备)
Draw centered text using core graphics (mobile device)
我正在使用此代码:
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 创建居中的 "text"。
但我不确定如何编辑上面的代码才能真正实现居中对齐,因为到目前为止文本根本没有真正居中。
抱歉,对于这种愚蠢的问题,但我没有找到该问题的工作示例,而且我是 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]];
我正在使用此代码:
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 创建居中的 "text"。
但我不确定如何编辑上面的代码才能真正实现居中对齐,因为到目前为止文本根本没有真正居中。
抱歉,对于这种愚蠢的问题,但我没有找到该问题的工作示例,而且我是 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]];