使用核心图形绘制居中文本(移动设备) [英] Draw centered text using core graphics (mobile device)

查看:42
本文介绍了使用核心图形绘制居中文本(移动设备)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码:

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创建居中的文本。

to create a centered "text" for iOS.

但是我不确定如何编辑上面的代码以真正使中心对齐工作,因为到目前为止,文本还没有真正居中。

But I'm not sure how to edit the code above to really get the center alignment working, because till now the text is not really centered at all.

对不起,对于那种愚蠢的问题,但我没有找到解决该问题的有效示例。我是使用Core Graphics的新手。

Sorry, for the kind of stupid question but I didn't found an working example for the problem & I'm new in using Core Graphics.

推荐答案

您的文本未居中,因为您必须从屏幕上减去文本宽度大小,然后必须除以2。下面我尝试纠正您的代码。

Your text is not centered because you have to subtract the text width from the screen size and then you have to divide by 2. Below I have tried to correct your 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]];

这篇关于使用核心图形绘制居中文本(移动设备)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆