OGeek|极客世界-中国程序员成长平台

标题: ios - 使用objective-c/core图形的水平居中文本 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:32
标题: ios - 使用objective-c/core图形的水平居中文本

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



Best Answer-推荐答案


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

  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图形的水平居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48035494/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4