• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Pigghaj · May 23, 2013 at 01:08 AM · guiiostextgui.labelcentering

Problem with centering text

Hi,

Here's the problem I've run into. I am doing an iOS card based 2D game. Since it's card-based it has a number of cards in it. Each card has about 3 to 6 lines of text.

I am using GUI.Label to show the text, and it's centering using the alignment setting in my GUIStyle. So far so good, everyt$$anonymous$$ng is working fine, the text is presented as it should, and it's centered. HOWEVER... t$$anonymous$$s happens with the text on many of my cards.

    "T$$anonymous$$s is a centered text meant 
   to show my problem regarding 
   centering of text. The problem 
    is that sometimes it looks like
                t$$anonymous$$s."
 

Last line? Not so good... just one word appears on the last line. Sometimes it's two, sometimes it's three, sometimes it ends up looking good. All lines are filled with as many words that fit, and the last line will simply hold as many words that are left to show, no matter if it looks good or not. T$$anonymous$$s isnt exactly wrong, thats how word processors do it. But... its not very nice looking. I want it to look like t$$anonymous$$s:

   "T$$anonymous$$s is a centered text meant 
    to show my problem regarding 
   centering of text. T$$anonymous$$s is how
   I would like it to look. Good!"
        

EVENLY centered text.

I store each card tex in a string, one big line of text, I could manually add a bunch of newlines in every string of course, but that would be painfully slow to do since there's a lot of cards, and if I wanted to change some text later I'd need to manually align it again.

So anyone has a suggestion how to automatically align a centered text evenly?

Thanks

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Coderdood · May 23, 2013 at 09:54 PM

T$$anonymous$$s is actually quite a bit harder than I thought but here is my stab at it. First some disclaimers:

Disclaimers

  • T$$anonymous$$s code is more of a 'proof of concept' and probably could be optimized / improved quite a bit and isn't the type of t$$anonymous$$ng you should really run every frame.

  • There are scenarios in w$$anonymous$$ch t$$anonymous$$s code generates similar bad looking text as unity depending on the length of the words in the text / etc. It might be possible to improve t$$anonymous$$s by allowing words to be broken into pieces but for readability I suggest keeping words intact.


    Full Test Code

The following code draws two text boxes - the one on the left uses Unity3D standard label the other one uses some code to format the text before drawing. I added a button so that you can toggle between growing / shrinking the labels to see how the word wrap works at various sizes.

alt text

 using UnityEngine;
 using System.Collections;
 
 public class TestDraw : MonoBehaviour 
 {
     Vector2 area = new Vector2(275.0f, 200.0f);
     bool grow = false;
     
     void OnGUI()
     {
         // Common content
         string testContent = "T$$anonymous$$s is a centered text meant to show my problem regarding centering of text. The problem is that sometimes it looks like t$$anonymous$$s.";
         if(!grow) { area.x -= 0.05f; } else { area.x += 0.05f; }
 
         // Bad text alignment
         Rect badDisplayArea = new Rect(5.0f, 5.0f, area.x, area.y);
         GUI.skin.label.alignment = TextAnchor.MiddleCenter;
         GUI.Box(badDisplayArea, "");
         GUI.Label(badDisplayArea, testContent);
         
         // Good text alignment
         Rect goodDisplayArea = new Rect(area.x + 10.0f, 5.0f, area.x, area.y);
         GUI.skin.label.alignment = TextAnchor.MiddleCenter;
         GUI.Box(goodDisplayArea, "");
         DrawCenteredText(testContent, goodDisplayArea);
         
         // Toggle shrinking / grow
         if( GUI.Button(new Rect( 5.0f, area.y + 50.0f, 50.0f, 50.0f), "Toggle\nGrow")) { grow = !grow; }
     }
     
     // Note t$$anonymous$$s function will only be work inside an OnGUI method or inside of another method used by OnGUI
     private void DrawCenteredText(string textToDraw, Rect textArea)
     {
         // Get the style we are using for the text
         GUIStyle getStyle = GUI.skin.GetStyle("Label");
         
         // Store text alignment
         TextAnchor storeAlignment = getStyle.alignment;
         getStyle.alignment = TextAnchor.MiddleCenter;
         
         // Create the content object to prevent duplicate 'new GUIContent(textToDraw)' calls
         GUIContent textContent = new GUIContent(textToDraw);
         
         // Figure out the width of the text without clipping it
         float textWidth = getStyle.CalcSize(textContent).x;
         
         // Figure out the height of the text with clipping
         float textHeight = getStyle.CalcHeight(textContent, textArea.width);
         
         // Figure out the average line width
         float lineCount = (textHeight / getStyle.lineHeight) - 0.25f; // Modify 0.25f for fine tuning
         float averageLineWidth = textWidth / lineCount;
         
         // Go through and construct the centered text
         string resultText = "";
         string centeredLine = "";
         float currentLineWidth = 0.0f;
         string[] wordsInText = textToDraw.Split(' ');
         for(int i = 0; i < wordsInText.Length; i++)
         {
             float wordSize = getStyle.CalcSize(new GUIContent(wordsInText[i])).x;
             
             // Add the line if the word will make it go over
             if(currentLineWidth + wordSize > averageLineWidth)
             {
                 // Add the line to the result
                 resultText += centeredLine + "\n";
                 
                 // Reset line and width
                 centeredLine = "";
                 currentLineWidth = 0.0f;
             }
             currentLineWidth += wordSize;
             centeredLine += wordsInText[i] + " ";
         }
 
         // Add the line to the result
         resultText += centeredLine;
 
         // Draw the text
         GUI.Label(textArea, resultText);
         
         // Restore alignment
         getStyle.alignment = storeAlignment;
     }
 }


What Does The Code Do?

My approach was to find out how wide text being displayed is along with how many lines the text is being displayed over and then figure out an average line width and add a new line to any line that will be larger than the average line width.

Knowing that the code should be somewhat self explanatory (I hope).

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Pigghaj · May 25, 2013 at 01:04 PM 0
Share
avatar image Pigghaj · Jun 07, 2013 at 01:46 PM 0
Share

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

14 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Text rendering bug. Shows black squares. -1 Answers

iOS performance: GUItext? want to use text string, but how to instantiate and edit it runtime? 0 Answers

GUI Label Width & Height 0 Answers

Can't draw GUI.Label text on subpixel values 0 Answers

Using "fonts" that are actually images for a multi-outline effect. 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges