FontCache.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. namespace WXB
  5. {
  6. public static class FontCache
  7. {
  8. static CharacterInfo s_Info;
  9. // 行高缓存
  10. static Dictionary<long, int> FontLineHeight = new Dictionary<long, int>();
  11. static TextGenerator sCachedTextGenerator = new TextGenerator();
  12. static public int GetLineHeight(Font font, int size, FontStyle fs)
  13. {
  14. long key = (long)(((ulong)fs) | (((ulong)size) << 24) | (((ulong)font.GetInstanceID()) << 32));
  15. int lineHeight = 0;
  16. if (FontLineHeight.TryGetValue(key, out lineHeight))
  17. return lineHeight;
  18. var settings = new TextGenerationSettings();
  19. settings.generationExtents = new Vector2(1000, 1000);
  20. if (font != null && font.dynamic)
  21. {
  22. settings.fontSize = size;
  23. }
  24. // Other settings
  25. settings.textAnchor = TextAnchor.LowerLeft;
  26. settings.lineSpacing = 1f;
  27. settings.alignByGeometry = false;
  28. settings.scaleFactor = 1f;
  29. settings.font = font;
  30. settings.fontSize = size;
  31. settings.fontStyle = fs;
  32. settings.resizeTextForBestFit = false;
  33. settings.updateBounds = false;
  34. settings.horizontalOverflow = HorizontalWrapMode.Overflow;
  35. settings.verticalOverflow = VerticalWrapMode.Truncate;
  36. string text = "a\na";
  37. sCachedTextGenerator.Populate(text, settings);
  38. IList<UIVertex> verts = sCachedTextGenerator.verts;
  39. #if UNITY_2019 || UNITY_2019_1_OR_NEWER
  40. lineHeight = (int)(verts[0].position.y - verts[4].position.y);
  41. #else
  42. lineHeight = (int)(verts[0].position.y - verts[8].position.y);
  43. #endif
  44. FontLineHeight.Add(key, lineHeight);
  45. return lineHeight;
  46. }
  47. static Dictionary<long, int> FontAdvances = new Dictionary<long, int>();
  48. static public int GetAdvance(Font font, int size, FontStyle fs, char ch)
  49. {
  50. long key = (long)(((ulong)((uint)ch)) | (((ulong)fs) << 16) | (((ulong)size) << 24) | (((ulong)font.GetInstanceID()) << 32));
  51. int advance = 0;
  52. if (FontAdvances.TryGetValue(key, out advance))
  53. return advance;
  54. for (int i = 0; i < 2; ++i)
  55. {
  56. if (font.GetCharacterInfo(ch, out s_Info, size, fs))
  57. {
  58. advance = (short)(s_Info.advance);
  59. FontAdvances.Add(key, advance);
  60. return advance;
  61. }
  62. else
  63. {
  64. font.RequestCharactersInTexture(new string(ch, 1), size, fs);
  65. }
  66. }
  67. FontAdvances.Add(key, 0);
  68. return 0;
  69. }
  70. }
  71. }