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

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

“Arial”,

“Helvetica”,

"Georgia",

"Courier New",

"Marker Felt",

"Times New Roman",

"Trebuchet MS",

"Verdana",

"Zapfino"。


- (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
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值