Draw centered text using core graphics (mobile device)

好久不见. 提交于 2020-01-03 05:14:09

问题


I'm using this code:

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]];

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.

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.


回答1:


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]];


来源:https://stackoverflow.com/questions/48034940/draw-centered-text-using-core-graphics-mobile-device

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!