CustomFontImportor.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Xml;
  4. using System;
  5. public class CustomFontImportor : MonoBehaviour
  6. {
  7. public Font font;
  8. public TextAsset textAsset;
  9. void Awake()
  10. {
  11. if (font == null || textAsset == null)
  12. {
  13. //Debug.LogError("请设置font和textAsset.");
  14. return;
  15. }
  16. XmlDocument xmlDocument = new XmlDocument();
  17. xmlDocument.LoadXml(textAsset.text);
  18. int totalWidth = Convert.ToInt32(xmlDocument["font"]["common"].Attributes["scaleW"].InnerText);
  19. int totalHeight = Convert.ToInt32(xmlDocument["font"]["common"].Attributes["scaleH"].InnerText);
  20. XmlElement xml = xmlDocument["font"]["chars"];
  21. ArrayList characterInfoList = new ArrayList();
  22. for (int i = 0; i < xml.ChildNodes.Count; ++i)
  23. {
  24. XmlNode node = xml.ChildNodes[i];
  25. if (node.Attributes == null)
  26. {
  27. continue;
  28. }
  29. int index = Convert.ToInt32(node.Attributes["id"].InnerText);
  30. int x = Convert.ToInt32(node.Attributes["x"].InnerText);
  31. int y = Convert.ToInt32(node.Attributes["y"].InnerText);
  32. int width = Convert.ToInt32(node.Attributes["width"].InnerText);
  33. int height = Convert.ToInt32(node.Attributes["height"].InnerText);
  34. int xOffset = Convert.ToInt32(node.Attributes["xoffset"].InnerText);
  35. int yOffset = Convert.ToInt32(node.Attributes["yoffset"].InnerText);
  36. int xAdvance = Convert.ToInt32(node.Attributes["xadvance"].InnerText);
  37. CharacterInfo info = new CharacterInfo();
  38. Rect uv = new Rect();
  39. uv.x = (float)x / totalWidth;
  40. uv.y = (float)(totalHeight - y - height) / totalHeight;
  41. uv.width = (float)width / totalWidth;
  42. uv.height = (float)height / totalHeight;
  43. info.index = index;
  44. info.uvBottomLeft = new Vector2(uv.xMin, uv.yMin);
  45. info.uvBottomRight = new Vector2(uv.xMax, uv.yMin);
  46. info.uvTopLeft = new Vector2(uv.xMin, uv.yMax);
  47. info.uvTopRight = new Vector2(uv.xMax, uv.yMax);
  48. info.minX = xOffset;
  49. info.maxX = xOffset + width;
  50. info.minY = -yOffset - height;
  51. info.maxY = -yOffset;
  52. info.advance = xAdvance;
  53. info.glyphWidth = width;
  54. info.glyphHeight = height;
  55. characterInfoList.Add(info);
  56. }
  57. font.characterInfo = characterInfoList.ToArray(typeof(CharacterInfo)) as CharacterInfo[];
  58. Debug.Log("生成成功.");
  59. }
  60. }