简体   繁体   English

iOS NSString drawInRect始终在RectFrame顶部下方绘制文本

[英]iOS NSString drawInRect always drawn text below the top of RectFrame

I have a method below to draw a text (the text is "0%", font size = 30) in a RectFrame (width = 170, height = 30): 我下面有一种方法可以在RectFrame(宽度= 170,高度= 30)中绘制文本(文本为“ 0%”,字体大小= 30):

/* Draw String IOS 7 up */
-(void) drawString: (CGRect) contextRect withStr: (NSString *) string {
    NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    textStyle.lineBreakMode = NSLineBreakByWordWrapping;
    textStyle.alignment = NSTextAlignmentCenter;

    UIFont *font = [UIFont systemFontOfSize:_textSize];
    UIColor* textColor = [UIColor grayColor];

    NSDictionary* stringAttrs = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:textStyle, NSForegroundColorAttributeName:textColor};
    [string drawInRect:contextRect withAttributes:stringAttrs];
}

I can not post the image result but the result is that the text is drawn some pixels below the top of the frame but the bottom is fine (text bottom match with the bottom frame), and no matter how I adjust both the sizes of frame and text, it always drawn "somewhere" below the frame top, any ideas? 我无法发布图像结果,但是结果是在边框的顶部下方一些像素处绘制了文本,但底部很好(文本底部与底部边框相匹配),无论我如何调整边框的大小和文字,它总是在框架顶部下方的“某处”绘制,有什么想法吗?

This is how it's intended to work. 这就是它的预期工作方式。 It always draws a few pixels below the top of the rect. 它总是在矩形顶部下方绘制几个像素。

If you want more control over positioning, you can use CTTypesetter and other Core Text APIs for calculating text sizes. 如果要对定位进行更多控制,可以使用CTTypesetter和其他Core Text API计算文本大小。 Here is a "simple" example: 这是一个“简单”的例子:

http://www.snip2code.com/Snippet/15903/Simple-CoreText-with-CTLineDraw-and-CTRu/ http://www.snip2code.com/Snippet/15903/Simple-CoreText-with-CTLineDraw-and-CTRu/

If you're going to use core text, be sure to read Apple's documentation: https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/CoreText_Programming/Overview/Overview.html#//apple_ref/doc/uid/TP40005533-CH3-SW1 如果您要使用核心文字,请务必阅读Apple的文档: https : //developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/CoreText_Programming/Overview/Overview.html#//apple_ref/doc / uid / TP40005533-CH3-SW1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM