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

 

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

分类: IOS 应用   162人阅读  评论(0)  收藏  举报

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

“Arial”,

“Helvetica”,

"Georgia",

"Courier New",

"Marker Felt",

"Times New Roman",

"Trebuchet MS",

"Verdana",

"Zapfino"。


[cpp]  view plain copy
  1. - (void)computeWidthAndHeight:(CGContextRef) context   
  2.                      withFont:(NSString *)fontName   
  3.                      withSize:(NSInteger)fontSize   
  4.                      string:(NSString *)str  
  5. {  
  6.     int strLength = [str length];  
  7.       
  8.     CGFontRef fontRef = CGFontCreateWithFontName((CGStringRef) fontName);   // create a system font  ref  
  9.     if (!fontRef)  
  10.     {  
  11.         NSLog(@"Warning : missing font %@",fontName);  
  12.         return;  
  13.     }  
  14.       
  15.     CGRect bbox = CGFontGetFontBBox(fontRef);           // return a box that can contain any char with this font  
  16.     int units = CGFontGetUnitsPerEm(fontRef);           // return how many glyph unit represent a system device unit  
  17.       
  18.     CGFloat height = (((float)bbox.size.height)/((float)units))*fontSize;   // compute the char height  
  19.       
  20.     CGContextSaveGState(context);                                           // save current context state  
  21.       
  22.     // use the invisible way to draw the str  
  23.     CGPoint left = CGContextGetTextPosition(context);                       // get the current context position  
  24.     CGContextSetTextDrawingMode(context, kCGTextInvisible);                         // 1 step  
  25.     CGContextSetTextMatrix(context, CGAffineTransformIdentity);                     // 2 step  
  26.     CGContextSelectFont(context, [font UTF8String], fontSize, KCGEncodingMacRoman); // 3 step  
  27.     // CGContextSetRGBStrokeColor();                                // 4 step  can be omitted  
  28.     // CGContextSetRGBFillColor();  
  29.     CGContextShowText(context, [str UTF8String], strLength);                // 5 step, default at current position  
  30.     // CGContextShowTextAtPoint();                                          // alse can work  
  31.     CGPoint right = CGContextGetTextPosition(context);                      // get the end context position  
  32.       
  33.     CGContextRestoreGState(context);                                // restore the before context state  
  34.       
  35.     CGFolat width = right.x - left.x;                               // compute the char width  
  36.       
  37.     CGFontRelease(fontRef);                                         // release font ref  
  38. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值