我正在尝试使用 Core Graphics 将文本置于 iPhone 屏幕的中央,我发现了 this code .
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]];
但是为我自己尝试这段代码我无法真正让它工作。文本并没有真正居中显示在我的屏幕上,我不知道如何编辑代码来解决我的问题。
这是我得到的结果:
最佳答案
这看起来基本上是正确的:一些小观察:
我不会引用
UIScreen
,而是引用呈现文本的 View 。例如。如果实际上在某些UIView
子类实现中,您只需引用self.bounds.size
。我会使用
attributes
再现,不仅获取边界矩形的大小,而且还获取drawAtPoint
。例如。使用drawAtPoint:withAttributes:
而不是drawAtPoint:withFont:
。字体颜色也应该是
attributes
字典的一部分。
例如:
CGSize viewSize = self.bounds.size;
NSString *text = @"text";
CGFloat minHeight = 40;
NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:22.0], NSForegroundColorAttributeName: [UIColor redColor]};
CGSize textSize = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, minHeight)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil].size;
[text drawAtPoint:CGPointMake((viewSize.width - textSize.width)/2, (viewSize.height - textSize.height)/2) withAttributes:attributes];
如果执行此操作后它仍然没有居中,则需要确认要在其中呈现它的 UIView
的 frame
,并确保它是你认为它应该在的地方。您可以在调试器中运行应用程序,然后使用 View 调试器 确认 View 所在的位置。
关于ios - 使用 objective-c/core graphics 的水平居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48035494/