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
}



你可能感兴趣的:(ios,String,iPhone,System,float)