1. 程式人生 > >[UGUI]圖文混排(二):下劃線

[UGUI]圖文混排(二):下劃線

otherwise ret align protected result pve amp HA fse

UGUI源碼:

https://bitbucket.org/Unity-Technologies/ui/downloads/?tab=tags

首先下載一份UGUI源碼,這裏我下載的版本是5.3.2f1。然後找到Text.cs,裏面有方法OnPopulateMesh,這個方法會修改文字的頂點。而圖文混排,涉及到頂點數據的修改。因此,我們的重點就是對這個方法進行修改,這裏給出一個最簡單的重寫版本,它和普通的text是一樣的。

 1 using System.Collections.Generic;
 2 using System.Text.RegularExpressions;
 3 using System.Text;
4 using UnityEngine.EventSystems; 5 using System; 6 using UnityEngine; 7 using UnityEngine.UI; 8 9 //下劃線<material=underline c=#ffffff h=1 n=*** p=***>blablabla...</material> 10 public class RichTextTest : Text { 11 private FontData m_FontData = FontData.defaultFontData; 12 13 readonly
UIVertex[] m_TempVerts = new UIVertex[4]; 14 protected override void OnPopulateMesh(VertexHelper toFill) 15 { 16 if (font == null) 17 return; 18 19 // We don‘t care if we the font Texture changes while we are doing our Update. 20 // The end result of cachedTextGenerator will be valid for this instance.
21 // Otherwise we can get issues like Case 619238. 22 m_DisableFontTextureRebuiltCallback = true; 23 24 Vector2 extents = rectTransform.rect.size; 25 26 var settings = GetGenerationSettings(extents); 27 cachedTextGenerator.Populate(text, settings); 28 29 Rect inputRect = rectTransform.rect; 30 31 // get the text alignment anchor point for the text in local space 32 Vector2 textAnchorPivot = GetTextAnchorPivot(m_FontData.alignment); 33 Vector2 refPoint = Vector2.zero; 34 refPoint.x = Mathf.Lerp(inputRect.xMin, inputRect.xMax, textAnchorPivot.x); 35 refPoint.y = Mathf.Lerp(inputRect.yMin, inputRect.yMax, textAnchorPivot.y); 36 37 // Determine fraction of pixel to offset text mesh. 38 Vector2 roundingOffset = PixelAdjustPoint(refPoint) - refPoint; 39 40 // Apply the offset to the vertices 41 IList<UIVertex> verts = cachedTextGenerator.verts; 42 float unitsPerPixel = 1 / pixelsPerUnit; 43 //Last 4 verts are always a new line... 44 int vertCount = verts.Count - 4; 45 46 toFill.Clear(); 47 if (roundingOffset != Vector2.zero) 48 { 49 for (int i = 0; i < vertCount; ++i) 50 { 51 int tempVertsIndex = i & 3; 52 m_TempVerts[tempVertsIndex] = verts[i]; 53 m_TempVerts[tempVertsIndex].position *= unitsPerPixel; 54 m_TempVerts[tempVertsIndex].position.x += roundingOffset.x; 55 m_TempVerts[tempVertsIndex].position.y += roundingOffset.y; 56 if (tempVertsIndex == 3) 57 toFill.AddUIVertexQuad(m_TempVerts); 58 } 59 } 60 else 61 { 62 for (int i = 0; i < vertCount; ++i) 63 { 64 int tempVertsIndex = i & 3; 65 m_TempVerts[tempVertsIndex] = verts[i]; 66 m_TempVerts[tempVertsIndex].position *= unitsPerPixel; 67 if (tempVertsIndex == 3) 68 toFill.AddUIVertexQuad(m_TempVerts); 69 } 70 } 71 m_DisableFontTextureRebuiltCallback = false; 72 } 73 }

可以看到,頂點的數據在cachedTextGenerator中,打印一下,會發現1個字符有4個頂點,而頂點的排列如下:

技術分享圖片

[UGUI]圖文混排(二):下劃線