ios - 使用 objective-c/core graphics 的水平居中文本

标签 ios objective-c core-graphics

我正在尝试使用 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]];

但是为我自己尝试这段代码我无法真正让它工作。文本并没有真正居中显示在我的屏幕上,我不知道如何编辑代码来解决我的问题。

这是我得到的结果:

image

最佳答案

这看起来基本上是正确的:一些小观察:

  1. 我不会引用 UIScreen,而是引用呈现文本的 View 。例如。如果实际上在某些 UIView 子类实现中,您只需引用 self.bounds.size

  2. 我会使用 attributes 再现,不仅获取边界矩形的大小,而且还获取 drawAtPoint。例如。使用 drawAtPoint:withAttributes: 而不是 drawAtPoint:withFont:

  3. 字体颜色也应该是 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];

如果执行此操作后它仍然没有居中,则需要确认要在其中呈现它的 UIViewframe,并确保它是你认为它应该在的地方。您可以在调试器中运行应用程序,然后使用 View 调试器 view debugger确认 View 所在的位置。

关于ios - 使用 objective-c/core graphics 的水平居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48035494/

相关文章:

ios - 如何向添加到 tableview 单元格的减号图像添加可访问性标签?

ios - 仅在满足条件时触发本地通知

ios - 使用 AVPlayer 播放本地 GIF

ios - Firebase 3 更新本地缓存

java - Objective-C 中的策略设计模式

objective-c - Objective-J 是否支持像 Objective-C 这样的协议(protocol)?

iphone - 仅允许在核心图条形图中水平滚动?

iphone - 使用 Quartz 2D 绘图时的模糊效果

ios - 随机移动应用图标生成算法

ios - 我的 Answer SDP(WebRTC、iOS 项目)有什么问题