您的位置:首页 > 移动开发 > IOS开发

IOS 根据 指定的 字体类型 ,size ,计算 绘制 文本 所需要的 宽度与高度

2012-10-24 14:03 591 查看


IOS 根据 指定的 字体类型 ,size ,计算 绘制 文本 所需要的 宽度与高度

分类: IOS 应用2012-09-13
20:15 162人阅读 评论(0) 收藏 举报

Iphone 允许 我们直接用于字体实例变量 的 字体类型(NSString) 有 :

“Arial”,

“Helvetica”,

"Georgia",

"Courier New",

"Marker Felt",

"Times New Roman",

"Trebuchet MS",

"Verdana",

"Zapfino"。

[cpp] view
plaincopy

- (void)computeWidthAndHeight:(CGContextRef) context

withFont:(NSString *)fontName

withSize:(NSInteger)fontSize

string:(NSString *)str

{

int strLength = [str length];



CGFontRef fontRef = CGFontCreateWithFontName((CGStringRef) fontName); // create a system font ref

if (!fontRef)

{

NSLog(@"Warning : missing font %@",fontName);

return;

}



CGRect bbox = CGFontGetFontBBox(fontRef); // return a box that can contain any char with this font

int units = CGFontGetUnitsPerEm(fontRef); // return how many glyph unit represent a system device unit



CGFloat height = (((float)bbox.size.height)/((float)units))*fontSize; // compute the char height



CGContextSaveGState(context); // save current context state



// use the invisible way to draw the str

CGPoint left = CGContextGetTextPosition(context); // get the current context position

CGContextSetTextDrawingMode(context, kCGTextInvisible); // 1 step

CGContextSetTextMatrix(context, CGAffineTransformIdentity); // 2 step

CGContextSelectFont(context, [font UTF8String], fontSize, KCGEncodingMacRoman); // 3 step

// CGContextSetRGBStrokeColor(); // 4 step can be omitted

// CGContextSetRGBFillColor();

CGContextShowText(context, [str UTF8String], strLength); // 5 step, default at current position

// CGContextShowTextAtPoint(); // alse can work

CGPoint right = CGContextGetTextPosition(context); // get the end context position



CGContextRestoreGState(context); // restore the before context state



CGFolat width = right.x - left.x; // compute the char width



CGFontRelease(fontRef); // release font ref

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: