场景
-
Cocoa
开发时, 往往需要在某个区域绘制文本, 但是文本的长度不是固定的, 所以有可能很长的时候需要自动换行.NSTextField
的[NSCell setWraps]
可以做到, 但是如果不能添加NSTextField
,只能通过绘制的方式?如何做.NSAttributeString
的size
只是单行的, 没什么用. -
宽度固定时,
Windows
开发时我们可以通过DT_CALCRECT
来计算高度,Cocoa
开发有没有相应的方法?
说明
Cocoa
也有相应的计算当宽度固定时区域文字高度的方法, 是通过NSLayoutManager
来实现的.
+(float) heightForStringDrawing:(NSString *)myString withFont:(NSFont *)myFont
withWidth:(float) myWidth
{
NSTextStorage *textStorage = [[[NSTextStorage alloc] initWithString:myString] autorelease];
NSTextContainer *textContainer = [[[NSTextContainer alloc]initWithContainerSize: NSMakeSize(myWidth, FLT_MAX)] autorelease];
NSLayoutManager *layoutManager = [[[NSLayoutManager alloc] init] autorelease];
[layoutManager addTextContainer:textContainer];
[textStorage addLayoutManager:layoutManager];
[textStorage addAttribute:NSFontAttributeName value:myFont range:NSMakeRange(0, [textStorage length])];
[textContainer setLineFragmentPadding:0.0];
(void) [layoutManager glyphRangeForTextContainer:textContainer];
return [layoutManager usedRectForTextContainer:textContainer].size.height;
}
// 在指定区域绘制文本, 需要自动换行.
+(void) drawStringInView:(NSString*)myString withFont:(NSFont *)myFont withRect:(NSRect)rect withColor:(NSColor*)color withAlign:(NSInteger)align
{
NSTextStorage *textStorage = [[NSTextStorage alloc]
initWithString:myString];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
NSTextContainer *textContainer = [[NSTextContainer alloc]initWithContainerSize: NSMakeSize(rect.size.width, FLT_MAX)];
[layoutManager addTextContainer:textContainer];
[textContainer release];
[textStorage addLayoutManager:layoutManager];
NSRange range = NSMakeRange(0, [textStorage length]);
[textStorage addAttribute:NSFontAttributeName value:myFont range:range];
[textStorage addAttribute:NSForegroundColorAttributeName value:color range:range];
NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
[style setAlignment:align];
[textStorage addAttribute:NSParagraphStyleAttributeName value:style range:range];
[layoutManager release];
NSRange glyphRange = [layoutManager
glyphRangeForTextContainer:textContainer];
float height = [layoutManager usedRectForTextContainer:textContainer].size.height;
[layoutManager drawGlyphsForGlyphRange: glyphRange atPoint: rect.origin];
[textStorage release];
// [style release];
}
// 调用方式
// [UiUtil drawStringInView:str_startup_tip_ withFont:font_15_bold_
// withRect:rect_startup_tip_ withColor:[NSColor blackColor] withAlign:NSCenterTextAlignment];
其他
Windows
GDI
GDIPlus
编程时计算文字高度的方法.
// GDI
int height = dc.DrawText(str_message_.c_str(),str_message_.size(), &rect_message_, DT_TOP| DT_WORDBREAK|DT_EDITCONTROL | DT_LEFT | DT_NOPREFIX|DT_CALCRECT);
// GDI+
graphics.MeasureString(str_desc.c_str(),str_desc.size(),&font_normal_bold_,
rectf_desc_temp,&rectf_desc);