cocoa – 如何在文本单元格中设置字体大小,以便字符串填充单元格的rect?

前端之家收集整理的这篇文章主要介绍了cocoa – 如何在文本单元格中设置字体大小,以便字符串填充单元格的rect?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个包含两个NSTextFieldCells的视图.绘制这些单元格的大小是从视图的大小派生的,我希望每个单元格中的文本最适合单元格的派生大小.这是我的,没有设置字体大小:
  1. - (void)drawRect:(NSRect)dirtyRect {
  2. /*
  3. * Observant readers will notice that I update the whole view here. If
  4. * there is a perceived performance problem,then I'll switch to just
  5. * updating the dirty rect.
  6. */
  7. NSRect boundsRect = self.bounds;
  8. const CGFloat monthHeight = 0.25 * boundsRect.size.height;
  9. NSRect monthRect = NSMakeRect(boundsRect.origin.x,boundsRect.origin.y + boundsRect.size.height
  10. - monthHeight,boundsRect.size.width,monthHeight);
  11. [monthCell drawWithFrame: monthRect inView: self];
  12.  
  13. NSRect dayRect = NSMakeRect(boundsRect.origin.x,boundsRect.origin.y,boundsRect.size.height - monthHeight);
  14. [dayCell drawWithFrame: dayRect inView: self];
  15.  
  16. [[NSColor blackColor] set];
  17. [NSBezierPath strokeRect: boundsRect];
  18. }

所以我知道我可以问一个字符串给定属性需要的大小,我知道我可以让控件改变它的大小以适应它的内容.这些都不适用:我希望内容(在这种情况下,单元格的stringValue)的大小适合已知的rect维度,以及实现未知的所需属性.如何找到所需的尺寸?假设我知道我将使用什么字体(因为我这样做).

更新注意:我不想截断字符串,我想增长或缩小它,以便整个事物适合,尽可能大的文本大小,提供给提供的矩形.

@R_301_323@

我使用一些类似的代码,但它处理不同的字体,大小高达10,000,并考虑到可用的高度以及文本显示区域的宽度.
  1. #define kMaxFontSize 10000
  2.  
  3. - (CGFloat)fontSizeForAreaSize:(NSSize)areaSize withString:(NSString *)stringToSize usingFont:(NSString *)fontName;
  4. {
  5. NSFont * displayFont = nil;
  6. NSSize stringSize = NSZeroSize;
  7. NSMutableDictionary * fontAttributes = [[NSMutableDictionary alloc] init];
  8.  
  9. if (areaSize.width == 0.0 || areaSize.height == 0.0) {
  10. return 0.0;
  11. }
  12.  
  13. NSUInteger fontLoop = 0;
  14. for (fontLoop = 1; fontLoop <= kMaxFontSize; fontLoop++) {
  15. displayFont = [[NSFontManager sharedFontManager] convertWeight:YES ofFont:[NSFont fontWithName:fontName size:fontLoop]];
  16. [fontAttributes setObject:displayFont forKey:NSFontAttributeName];
  17. stringSize = [stringToSize sizeWithAttributes:fontAttributes];
  18.  
  19. if (stringSize.width > areaSize.width)
  20. break;
  21. if (stringSize.height > areaSize.height)
  22. break;
  23. }
  24.  
  25. [fontAttributes release],fontAttributes = nil;
  26.  
  27. return (CGFloat)fontLoop - 1.0;
  28. }

猜你在找的HTML相关文章