示例#1
0
        /// <summary>
        /// Get the best fit size for this TMP_Text Component.
        /// </summary>
        /// <param name="text">The TMP_Text Component to get the best fit size of.</param>
        /// <param name="newStrings">List of strings which will be used in resizing calculations to ensure it is visible in this Text Component.</param>
        /// <returns>Returns the font size the Text has been set to.</returns>
        private static float GetBestFitSize(TMP_Text text, List <string> newStrings)
        {
            var smallestFontSize = 0f;
            var currentText      = text.text;

            if (newStrings == null)
            {
                newStrings = new List <string> {
                    currentText
                };
            }
            if (!newStrings.Contains(currentText))
            {
                newStrings.Add(currentText);
            }
            var bestFitBehaviour = text.GetComponentInParent <BestFit>();

            foreach (var s in newStrings)
            {
                text.text             = s;
                text.enableAutoSizing = true;
                text.fontSizeMin      = bestFitBehaviour ? bestFitBehaviour.MinFontSize : 1f;
                text.fontSizeMax      = bestFitBehaviour ? bestFitBehaviour.MaxFontSize : 1000f;
                //Set to max possible to start all text at an equal point.
                text.fontSize = text.fontSizeMax;
                //Force the text mesh to be updated.
                text.Rebuild(CanvasUpdate.PreRender);
                //Disable BestFit on Component.
                text.enableAutoSizing = false;
                var newSize = text.fontSize;
                //NewSizeRescale is used to scale down newSize if rect used for text is bigger than rect for the GameObject.
                var newSizeRescale = RescaleFontSize(text, 1f);
                //Multiply newSize by newSizeScale and round down to the nearest int.
                newSize *= newSizeRescale;
                //If newSize is smaller than the current smallestFontSize or if smallestFontSize has not been set, set smallestFontSize to equal newSize.
                if (newSize < smallestFontSize || Mathf.Approximately(smallestFontSize, 0))
                {
                    smallestFontSize = newSize;
                }
            }
            //Reset the text to display what it was previously.
            text.text = currentText;
            return(Mathf.Min(smallestFontSize, bestFitBehaviour ? bestFitBehaviour.MaxFontSize : 300));
        }