font.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #if defined(Hiro_Font)
  2. namespace hiro {
  3. auto pFont::size(const Font& font, const string& text) -> Size {
  4. @autoreleasepool {
  5. if(NSFont* nsFont = create(font)) {
  6. return size(nsFont, text);
  7. }
  8. }
  9. return {0, 0};
  10. }
  11. auto pFont::size(NSFont* font, const string& text) -> Size {
  12. @autoreleasepool {
  13. NSString* cocoaText = [NSString stringWithUTF8String:text];
  14. NSDictionary* fontAttributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
  15. NSSize size = [cocoaText sizeWithAttributes:fontAttributes];
  16. return {(int)size.width, (int)size.height};
  17. }
  18. }
  19. auto pFont::family(const string& family) -> string {
  20. if(family == Font::Sans ) return "Lucida Grande";
  21. if(family == Font::Serif) return "Georgia";
  22. if(family == Font::Mono ) return "Menlo";
  23. return "Lucida Grande";
  24. }
  25. auto pFont::create(const Font& font) -> NSFont* {
  26. auto fontName = family(font.family());
  27. NSString* family = [NSString stringWithUTF8String:fontName];
  28. CGFloat size = Application::scale(font.size() ? font.size() : 8);
  29. NSFontTraitMask traits = 0;
  30. if(font.bold()) traits |= NSBoldFontMask;
  31. if(font.italic()) traits |= NSItalicFontMask;
  32. //note: below properties are not exposed by hiro::Font; traits are saved here for possible future use
  33. //if(font.narrow()) traits |= NSNarrowFontMask;
  34. //if(font.expanded()) traits |= NSExpandedFontMask;
  35. //if(font.condensed()) traits |= NSCondensedFontMask;
  36. //if(font.smallCaps()) traits |= NSSmallCapsFontMask;
  37. size *= 1.5; //scale to point sizes (for consistency with other operating systems)
  38. return [[NSFontManager sharedFontManager] fontWithFamily:family traits:traits weight:5 size:size];
  39. }
  40. }
  41. #endif