Question

how to calculate string width in a web appliaction

Asked by: rakeshjaimini

hi,
i'm facing a nightmare issue in our menus

the menu is inside a div of fixed width of 180px
the menuitem text is creating the problem
right now menuitem text is truncated on the basis of no of character but this is not the solution as 'CCCC' takes more space then 'iiii'

the menuitem css used is
font-family:Arial, helvetica,Geneva, sans-serif;
font-size:.75em;

now I'm changing the logic of truncation of menuitem text by using width of the string but issues are
1.i need to calculate width of the string according to the client machine
2. client's monitor resolution+installed fonts should be taken care of

so as everything is  not possible so I'm trying to make an approximate approach by using MeasureString of graphics object but not getting the required result
i'm trying following code but cant make it complete

Bitmap bmForGraphics = new Bitmap(300, 300);
                    FontFamily fmServicenetMenuFont = new FontFamily("Arial");
                    Font fontServicenetMenuFont = new Font(fmServicenetMenuFont, 0.75f);
                    Graphics graphicsObject = System.Drawing.Graphics.FromImage(bmForGraphics);
                    graphicsObject.PageUnit = GraphicsUnit.Pixel;
                    //graphicsObject.PageScale = 1;
                    SizeF strTextWidth = graphicsObject.MeasureString(strText, fontServicenetMenuFont);

                                  
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-18 at 03:20:52ID24660871
Tags

C#

,

stringwidth

,

asp.net

Topics

C# Programming Language

,

Programming for ASP.NET

,

WebApplications

Participating Experts
3
Points
500
Comments
16

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. div width not playing ball...
    Can anybody give me a steer as to why the #advenqslide div isn't appearing as the same width as the #aboutdiv on my page here? I'm playing about with a layout, and some JS appear effects, and when the #advenqslide div appears it's about 10% narrower (width-wise)... can't fo...
  2. Measure string width in a machine that the font is not install…
    Hi. How can I measure string width in a PC that the desired font is NOT installed? I thought may be a way to get font properties in a machine that has the font and based on that info calculate string width on another machine that does not have the font. This is a web applicat...
  3. CSS Font Width Calculation
    Hi All, The issue that I've come across is that I have a label that displays the month of the year and I need to calculate the width of the month so that all months are approximately 130 pixels in length. What I was hoping to do is to change the letter-spacing style on the f...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: crazymanPosted on 2009-08-18 at 03:50:01ID: 25121724

Cant you just set the style of the div

overflow:hidden

Will stop the div from overflowing...

 

by: rakeshjaiminiPosted on 2009-08-18 at 03:55:40ID: 25121762

that wont work
i did this but the issue comes is the sub menus will open far away from its exact position also the black arrow image will not be shown in this case

the only solution is truncating the string with padding '...' in the end

 

by: sunithnairPosted on 2009-08-18 at 05:12:26ID: 25122321

Try using a Monospaced font like courier or courier new if possible.

 

by: rakeshjaiminiPosted on 2009-08-18 at 05:23:55ID: 25122405

not possible
have to use
font-family:Arial, helvetica,Geneva, sans-serif;
proportionately-spaced fonts

 

by: sunithnairPosted on 2009-08-18 at 06:15:14ID: 25122816

You could try something with javascript

http://stackoverflow.com/questions/282758/truncate-a-string-nicely-to-fit-within-a-given-pixel-width

<html>
<head>
<script type="text/javascript">
function fitStringToWidth(str,width,className) {
  // str    A string where html-entities are allowed but no tags.
  // width  The maximum allowed width in pixels
  // className  A CSS class name with the desired font-name and font-size. (optional)
  // ----
  // _escTag is a helper to escape 'less than' and 'greater than'
  function _escTag(s){ return s.replace("<","&lt;").replace(">","&gt;");}
 
  //Create a span element that will be used to get the width
  var span = document.createElement("span");
  //Allow a classname to be set to get the right font-size.
  if (className) span.className=className;
  span.style.display='inline';
  span.style.visibility = 'hidden';
  span.style.padding = '0px';
  document.body.appendChild(span);
 
  var result = _escTag(str); // default to the whole string
  span.innerHTML = result;
  // Check if the string will fit in the allowed width. NOTE: if the width
  // can't be determinated (offsetWidth==0) the whole string will be returned.
  if (span.offsetWidth > width) {
    var posStart = 0, posMid, posEnd = str.length, posLength;
    // Calculate (posEnd - posStart) integer division by 2 and
    // assign it to posLength. Repeat until posLength is zero.
    while (posLength = (posEnd - posStart) >> 1) {
      posMid = posStart + posLength;
      //Get the string from the begining up to posMid;
      span.innerHTML = _escTag(str.substring(0,posMid)) + '&hellip;';
 
      // Check if the current width is too wide (set new end)
      // or too narrow (set new start)
      if ( span.offsetWidth > width ) posEnd = posMid; else posStart=posMid;
    }
 
    result = '<abbr title="' +
      str.replace("\"","&quot;") + '">' +
      _escTag(str.substring(0,posStart)) +
      '&hellip;<\/abbr>';
  }
  document.body.removeChild(span);
  return result;
}
</script>
<style type="text/css">
.style1
{
font-family:Arial, helvetica,Geneva, sans-serif;
font-size:.75em; 
}
.style2
{
font-family:Times New Roman, helvetica,Geneva, sans-serif;
font-size:.75em; 
}
.style3
{
font-family:Courier, helvetica,Geneva, sans-serif;
font-size:.75em; 
}
</style>
</head>
<body>
<body>
<script type="text/javascript">
document.write(fitStringToWidth("This is just a test string",50,"style1") + "<br>")
document.write(fitStringToWidth("This is just a test string",50,"style2") + "<br>")
document.write(fitStringToWidth("This is just a test string",50,"style3") + "<br>")
alert(fitStringToWidth("This is just a test string",50,"style1"));
</script>
</html>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:

Select allOpen in new window

 

by: sunithnairPosted on 2009-08-18 at 06:17:53ID: 25122839

Updated example here

<html>
<head>
<script type="text/javascript">
function fitStringToWidth(str,width,className) {
  // str    A string where html-entities are allowed but no tags.
  // width  The maximum allowed width in pixels
  // className  A CSS class name with the desired font-name and font-size. (optional)
  // ----
  // _escTag is a helper to escape 'less than' and 'greater than'
  function _escTag(s){ return s.replace("<","&lt;").replace(">","&gt;");}
 
  //Create a span element that will be used to get the width
  var span = document.createElement("span");
  //Allow a classname to be set to get the right font-size.
  if (className) span.className=className;
  span.style.display='inline';
  span.style.visibility = 'hidden';
  span.style.padding = '0px';
  document.body.appendChild(span);
 
  var result = _escTag(str); // default to the whole string
  span.innerHTML = result;
  // Check if the string will fit in the allowed width. NOTE: if the width
  // can't be determinated (offsetWidth==0) the whole string will be returned.
  if (span.offsetWidth > width) {
    var posStart = 0, posMid, posEnd = str.length, posLength;
    // Calculate (posEnd - posStart) integer division by 2 and
    // assign it to posLength. Repeat until posLength is zero.
    while (posLength = (posEnd - posStart) >> 1) {
      posMid = posStart + posLength;
      //Get the string from the begining up to posMid;
      span.innerHTML = _escTag(str.substring(0,posMid)) + '&hellip;';
 
      // Check if the current width is too wide (set new end)
      // or too narrow (set new start)
      if ( span.offsetWidth > width ) posEnd = posMid; else posStart=posMid;
    }
 
    result = '<abbr title="' +
      str.replace("\"","&quot;") + '">' +
      _escTag(str.substring(0,posStart)) +
      '&hellip;<\/abbr>';
  }
  document.body.removeChild(span);
  return result;
}
</script>
<style type="text/css">
.style1
{
font-family:Arial, helvetica,Geneva, sans-serif;
font-size:.75em; 
}
.style2
{
font-family:Times New Roman, helvetica,Geneva, sans-serif;
font-size:.75em; 
}
.style3
{
font-family:Courier, helvetica,Geneva, sans-serif;
font-size:.75em; 
}
</style>
</head>
<body>
<body>
<script type="text/javascript">
document.write("<div class='style1'>" + fitStringToWidth("This is just a test string",50,"style1") + "</div><br>")
document.write("<div class='style2'>" + fitStringToWidth("This is just a test string",50,"style2") + "</div><br>")
document.write("<div class='style3'>" + fitStringToWidth("This is just a test string",50,"style3") + "</div><br>")
</script>
</html>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:

Select allOpen in new window

 

by: rakeshjaiminiPosted on 2009-08-18 at 06:22:06ID: 25122872

nice solution but i have already looked it earlier
the issue in this solution is my menu is a third party control so can use JavaScript but that wont be a feasible solution as i need to do lot of hardcoding(to get menuitem's text in javascript)  in that case also there is performance constraint so have to do it on server side

i have also tried
text-overflow:ellipsis
but it wont help my case

 

by: sunithnairPosted on 2009-08-18 at 07:02:03ID: 25123274

I think it can only be done on the client side and you could do something like this. This would infact be better (performance) than trying to do it on the server side (if it is possible at all).

<html>
<head>
<script type="text/javascript">
function fitStringToWidth(str,width,className) {
  // str    A string where html-entities are allowed but no tags.
  // width  The maximum allowed width in pixels
  // className  A CSS class name with the desired font-name and font-size. (optional)
  // ----
  // _escTag is a helper to escape 'less than' and 'greater than'
  function _escTag(s){ return s.replace("<","&lt;").replace(">","&gt;");}
 
  //Create a span element that will be used to get the width
  var span = document.createElement("span");
  //Allow a classname to be set to get the right font-size.
  if (className) span.className=className;
  span.style.display='inline';
  span.style.visibility = 'hidden';
  span.style.padding = '0px';
  document.body.appendChild(span);
 
  var result = _escTag(str); // default to the whole string
  span.innerHTML = result;
  // Check if the string will fit in the allowed width. NOTE: if the width
  // can't be determinated (offsetWidth==0) the whole string will be returned.
  if (span.offsetWidth > width) {
    var posStart = 0, posMid, posEnd = str.length, posLength;
    // Calculate (posEnd - posStart) integer division by 2 and
    // assign it to posLength. Repeat until posLength is zero.
    while (posLength = (posEnd - posStart) >> 1) {
      posMid = posStart + posLength;
      //Get the string from the begining up to posMid;
      span.innerHTML = _escTag(str.substring(0,posMid)) + '&hellip;';
 
      // Check if the current width is too wide (set new end)
      // or too narrow (set new start)
      if ( span.offsetWidth > width ) posEnd = posMid; else posStart=posMid;
    }
 
    result = '<abbr title="' +
      str.replace("\"","&quot;") + '">' +
      _escTag(str.substring(0,posStart)) +
      '&hellip;<\/abbr>';
  }
  document.body.removeChild(span);
  return result;
}
</script>
<style type="text/css">
.style1
{
font-family:Arial, helvetica,Geneva, sans-serif;
font-size:.75em; 
}
</style>
</head>
<body>
<div id="Menu1" class="style1">Visual Studio 2005</div>
<div id="Menu2" class="style1">SQL Server 2005</div>
<div id="Menu3" class="style1">Sharepoint 2007</div>
<div id="Menu4" class="style1">Microsoft Office 2007</div>
<div id="Menu5" class="style1">Visual Source Safe</div>
</body>
<script type="text/javascript">
var elements = document.getElementsByTagName("div");
for(var i=0;i<elements.length;i++)
{
    if(elements[i].id.indexOf("Menu") != -1)
        elements[i].innerHTML = fitStringToWidth(elements[i].innerHTML,100,"style1")
}
</script>
</html>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:

Select allOpen in new window

 

by: rakeshjaiminiPosted on 2009-08-18 at 07:08:02ID: 25123328

it can be done in server side code
i have attached code of the same
but this code need to be corrected
it's not working fine as i'm getting point values from measurestring method where pixel is expected

 

by: abelPosted on 2009-08-18 at 16:04:22ID: 25128416

It seems that this question has received quite some coverage, but let me get into a few things, if I may:

Solving this server side is not just hard, it is close to impossible. It is not (always) trivial to get the dpi, the screen size and the zoom size for a page, and getting the installed fonts is simply not featured through javascript or any other means, so that's off.

It is possible to use a method similar to MeasureString. There are several such around, for GDI, GDI+ and for OpenGL for instance. The tricky bit is: they all give (slightly) different results. This has to do with kerning and rounding, but can be significant on any string larger then a few characters.

Not sure it's mentioned here already, but if the word-breaking algorithm comes into play if the string doesn't fit the maximum width of the target element, all browsers will act differently, which adds to the impossibility of solving this task.

There are only very few cases where I know of that it is really necessary to know the size of a string after rendering. If you explain us the actual requirement, we may be of more help. You show screenshots of menus that become too wide. If breaking the string is not an option, then the only thing you can do is add overflow: hidden to the CSS class. But you said it doesn't help you. Why? Can we perhaps help you make it work?

You say performance is an issue, but you want to solve it server side. I may be missing the point here, but usually, when performance is an issue, you try to have the client side do a larger part of the job. Having the server do it, will vastly decrease overall performance and influence all users. Using a simple JS solution (as provided) will only marginally impact the client side and will not impoverise other user's experiences when many requests need to be served. But this is my view of the story, I may be wrong for your specific scenario.

In short: if you want to cut the text, you don't want to invest weeks in an impossible and never-stable solution, instead, you'd want to make sure the overflow style works (either through JS or though CSS). A one liner with a sure result against a full project with an uncertain result. Alternatively, if you feel like you must have the exact size, the solution by sunithnair is a common way to solve this, is easy to apply and does not require performance.

Sorry if this was not really what you wanted to hear, but I felt giving you a fair extra eye (read: opinion) on the problem matter was a good thing to do here.

-- Abel --

 

by: rakeshjaiminiPosted on 2009-08-18 at 23:11:26ID: 25129966

Hi, abel first of all thanks for replying.i think some point are not clear to you from my question

 It is not (always) trivial to get the dpi, the screen size and the zoom size for a page, and getting the installed fonts is simply not featured through javascript or any other means, so that's off.

things i can get on server side

the client machine current resolution(it is sent to server from login page-application always opened as maximized window)

Zoom size-->we assume it to be on default setting

client browser's text size-->we assume it to be on default setting

fonts-->font-family:Arial, helvetica,Geneva, sans-serif; (all fonts belongs to sans serif and  i have checked it that character width remains same for whole sans serif family)

browser-only IE

OS-windows only

Not sure it's mentioned here already, but if the word-breaking algorithm comes into play if the string doesn't fit the maximum width of the target element, all browsers will act differently, which adds to the impossibility of solving this task.

about word breaking algorithm -i will do it by approximation that's not the problem

browser is IE only so that's not the problem

If breaking the string is not an option, then the only thing you can do is add overflow: hidden to the CSS class. But you said it doesn't help you. Why?

check attached screenshot

also the solution given by the sunithnair is nice but it wont work in my scenrio reason being menu is a third party control and id's are generated like 'navBarLeftMenu_navBarLeftMenu_p_SubNavBarItem5_menuAdmin' also the rendered text is inside td which dont have id

can't dig it more coz this is third party control :(

You say performance is an issue, but you want to solve it server side.

this is the tricky part in normal scenrio JS gives you performace boost but in our case its just opposite

also the reason i gave above that its an third party control.

please find my comments in below code it would be grateful if you can correct it

Bitmap bmForGraphics = new Bitmap(300, 300);
                    FontFamily fmServicenetMenuFont = new FontFamily("Arial");//here we can use generic families
                    Font fontServicenetMenuFont = new Font(fmServicenetMenuFont, 0.75f);//i'm confused here the font size given in css is 0.75em how can i specify same over here
                    Graphics graphicsObject = System.Drawing.Graphics.FromImage(bmForGraphics);
                    graphicsObject.PageUnit = GraphicsUnit.Pixel;//this thing not working i'm getting strTextWidth in points
                    //graphicsObject.PageScale = 1;
                    SizeF strTextWidth = graphicsObject.MeasureString(strText, fontServicenetMenuFont);//here wen i give 'CCCCCCCCCCCCCCCCCCC'it returns me 18 what's this 18 is? is it in points or pixel?
                                              
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

 

by: rakeshjaiminiPosted on 2009-08-19 at 02:04:13ID: 25130700

hi, i have achieved little bit by the given code
but now i'm getting different string width on different resolution i know my local machine is server and client both but i just want to approximate the width

800X600      197
1024X768    197
1152X864    224
1280X768    197
1280X800    197
1280X960    224

can you tell me why this width varies

Bitmap bmForGraphics = new Bitmap(300, 300);
                    FontFamily fmServicenetMenuFont = new FontFamily(System.Drawing.Text.GenericFontFamilies.SansSerif);                    
                    Font fontServicenetMenuFont = new Font(fmServicenetMenuFont, 12,GraphicsUnit.Pixel);
                    Graphics graphicsObject = Graphics.FromImage(bmForGraphics);
                    graphicsObject.PageUnit = GraphicsUnit.Pixel;
                    //graphicsObject.PageScale = 1;
                    SizeF strTextWidth = graphicsObject.MeasureString(strText, fontServicenetMenuFont);
                    if (strText.Contains("CCCCCCCC"))

                                              
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window

 

by: rakeshjaiminiPosted on 2009-08-19 at 02:44:26ID: 25130900

hi, please skip last comment as i'm getting same width for all resolution by using following code

Bitmap bmForGraphics = new Bitmap(300, 300);
                    FontFamily fmServicenetMenuFont = new FontFamily(System.Drawing.Text.GenericFontFamilies.SansSerif);                    
                    Font fontServicenetMenuFont = new Font(fmServicenetMenuFont, 12,GraphicsUnit.Pixel);
                    Graphics graphicsObject = Graphics.FromImage(bmForGraphics);
                    graphicsObject.PageUnit = GraphicsUnit.Pixel;
                    //graphicsObject.PageScale = 1;
                    SizeF strTextWidth = graphicsObject.MeasureString(strText, fontServicenetMenuFont);

                                              
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

 

by: abelPosted on 2009-08-19 at 02:53:56ID: 25130938

The MeasureString gives a size (coordinates) that have units relative to the chosen 2D viewport. This is a GDI+ method and I don't think it is good to use it here, it will be quite hard to calculate the correct values from it.

Instead, use TextRenderer.MeasureText. This is a static method, uses GDI (not GDI+) which seems more appropriate for your situation. It also returns a value directly in pixels instead of a relative coordinate system. Something like the following should suit your needs:

Bitmap bmForGraphics = new Bitmap(300, 300);
FontFamily fmServicenetMenuFont = new FontFamily(System.Drawing.Text.GenericFontFamilies.SansSerif);                    
Font fontServicenetMenuFont = new Font(fmServicenetMenuFont, 12,GraphicsUnit.Pixel);
Size strTextSize = TextRenderer.MeasureText(strText, fontServicenetMenuFont);
                                              
1:
2:
3:
4:

Select allOpen in new window

 

by: abelPosted on 2009-08-19 at 02:59:16ID: 25130962

PS: you can remove line 1 in my last code snippet.

If you feel like you should give a bounding rectangle (to know how the word breaks) you can use a third parameter which takes a Size object.

Thanks for going into details about my questions. I don't concur with your conclusions (the hard-to-get id names and the td not having an id can be worked around with using jQuery) but the way you put it, it seems that the front side is heavy as it is. But, more importantly, the overflow CSS style is not applied correctly. Puzzling that one out with FireBug in Firefox (I know you use IE) then you have a much leaner and meaner solution...

 

by: rakeshjaiminiPosted on 2009-08-19 at 07:52:53ID: 31656996

Thanks For your kind help
i'm using graphicsObject.MeasureString for now if i face any issue will switch to  TextRenderer.MeasureText

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...