Ios 使用核心图形绘制居中文本(移动设备)
我正在使用以下代码:Ios 使用核心图形绘制居中文本(移动设备),ios,objective-c,core-graphics,Ios,Objective C,Core Graphics,我正在使用以下代码: CGRect screenRect = [[UIScreen mainScreen] bounds]; CGFloat screenWidth = screenRect.size.width; CGFloat screenHeight = screenRect.size.height; NSString * text = @"text"; CGContextSetFillColorWithColor(context, [UIColor colorWithRed:1 gree
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创建居中的“文本”
但是我不确定如何编辑上面的代码来真正实现中心对齐,因为到目前为止,文本根本没有真正居中
抱歉,对于这类愚蠢的问题,我没有找到解决这个问题的有效示例&我对使用核心图形是新手。您的文本没有居中,因为您必须从屏幕大小中减去文本宽度,然后再除以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]];
文本未居中,因为必须从屏幕大小中减去文本宽度,然后除以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]];
顺便说一下,正如我在对的回答中指出的,(a)您不应该使用
drawAtPoint:withFont:
,而应该使用drawAtPoint:withAttributes:
;(b)您应该在属性
字典中指定字体颜色,而不是在CoreGraphics API中。顺便说一下,正如我在对的回答中指出的那样,(a)您不应该使用drawAtPoint:withFont:
,而应该使用drawAtPoint:withAttributes:
;(b)您应该在属性
字典中指定字体颜色,而不是在CoreGraphics API中。