1

I need to know how to get a string's length in pixels in C# Unity3D.

  string msg = ""You Must be from South Carolina!";

How do I get the above message string length in Pixels?.

Nick Udell
  • 2,420
  • 5
  • 44
  • 83
user3666257
  • 33
  • 2
  • 7
  • First, what have you already tried. Second, the size of text in pixels will depend on (at the very least) the rendering method. So a good start would be to specify how you're actually rendering this string onscreen. – Nick Udell May 27 '14 at 09:15
  • Something similar was already answered here before: http://stackoverflow.com/questions/451903/how-can-i-convert-a-string-length-to-a-pixel-unit Hopefully this helps you. – Fireboyd78 May 27 '14 at 09:16

1 Answers1

2

Here is a way you can get the width of your String. Nb: You should know what font you use :

string msg = "You Must be from South Carolina!";
Font stringFont = new Font("Arial", 12);

using (Bitmap tempImage = new Bitmap(400,400)) 
{
    SizeF stringSize = Graphics.FromImage(tempImage).MeasureString(msg , stringFont);
    double width = stringSize.Width;
}
Perfect28
  • 11,089
  • 3
  • 25
  • 45
  • Which Name space `SizeF` avaialble?.@Ksven. – user3666257 May 27 '14 at 09:22
  • It's in System.Drawing. You should reference the assembly System.Drawing.dll if it's not the case. – Perfect28 May 27 '14 at 09:23
  • I got This error : The type or namespace name `SizeF' could not be found. Are you missing a using directive or an assembly reference?.So what i can do for this?.@Ksven – user3666257 May 27 '14 at 09:40
  • You need to add a using statement to the top of your code, e.g. using System.Drawing and you should add a reference to System.Drawing.DLL if its not already referenced. – Nick Udell May 27 '14 at 09:54