【问题标题】:iOS NSString drawInRect always drawn text below the top of RectFrameiOS NSString drawInRect 总是在 RectFrame 顶部下方绘制文本
【发布时间】:2014-08-09 10:19:42
【问题描述】:

我有下面的方法在 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];
}

我无法发布图像结果,但结果是文本在框架顶部下方绘制了一些像素但底部很好(文本底部与底部框架匹配),无论我如何调整框架和文本的大小,它总是画在框架顶部下方的“某处”,有什么想法吗?

【问题讨论】:

    标签: ios objective-c nsstring alignment drawinrect


    【解决方案1】:

    这就是它的工作方式。它总是在矩形顶部下方绘制几个像素。

    如果您想更好地控制定位,可以使用CTTypesetter 和其他 Core Text API 来计算文本大小。这是一个“简单”的例子:

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

    如果您要使用核心文本,请务必阅读 Apple 的文档:https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/CoreText_Programming/Overview/Overview.html#//apple_ref/doc/uid/TP40005533-CH3-SW1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      相关资源
      最近更新 更多