I have a method below to draw a text (the text is "0%", font size = 30) in a RectFrame (width = 170, height = 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. Here is a "simple" example:
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