This project has moved and is read-only. For the latest updates, please go here.

How to set label at the mid of a line

Topics: Algorithms, SharpMap Project, SharpMap v0.9 / v1.x, SharpMap v2.0, Web Controls, WinForms Controls
Jul 2, 2009 at 3:33 AM

Hi everybody,

I want to put a label at the mid of a line as folowing:

(x1,y1) ---(my label)--- (x2,y2)


I set Geometry of label is (x1+x2)/2, (y1+y2)/2. But it still displays wrong position.

Maybe geometry of label must be (x1+x2)/2 - length(my label)/2. But I don't know how to get length of label.


Anyone help me


Thanks for any reply !



Jul 2, 2009 at 10:57 AM

Hi nguyen1phuong, have you seen the LabelLayer.MultiPartGeometryBehavior, LabelStyle.[Horizontal|Vertical]Alignment ? If they don't work and you still need to measure the string you will need to use Graphics.MeasureString though this may require a bit of customisation to get a handle on the graphics object being used also note that MeasureString is a pretty slow call.


hth jd

Jul 3, 2009 at 8:03 AM

Hi johndiss,

Thanks for your reply, I tried MeasureString but  they don't work. Here is my code

SharpMap.Data.FeatureDataRow row = this.tbl.NewRow();
row["ID"] = toNode.ID.ToString();
strName = fromNode.ID.ToString() + "->" + toNode.ID.ToString();
row["Name"] = strName;
System.Drawing.SizeF textsize = g.MeasureString(strName, font);

row.Geometry = new SharpMap.Geometries.Point((fromNode.Position.X + toNode.Position.X) / 2 - textsize.Width / 2, (fromNode.Position.Y + toNode.Position.Y) / 2 - textsize.Height / 2) ;

this.layerLabel.Style = new SharpMap.Styles.LabelStyle();
this.layerLabel.Style.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Center;
this.layerLabel.Style.VerticalAlignment = SharpMap.Styles.LabelStyle.VerticalAlignmentEnum.Top;
this.dataProviderTopo = new SharpMap.Data.Providers.GeometryFeatureProvider(this.tbl);
this.layerLabel.DataSource = this.dataProviderTopo;


The problem is MeasureString function. The textsize.Width and textsize.Height are so big. For example, fromNode.Position.X =5 toNode.Position.X=10 and textsize.Width=70 ? Maybe i need a scale for MeasureString function?


Jul 3, 2009 at 10:32 AM

Remember that Graphics.MeasureString returns a result in the screen / image pixels whereas the geometries are in real world coordinates. You will need to use Map.ImageToWorld and Map.WorldToImage to convert between the two reference systems.. hth jd 

May 11, 2010 at 2:27 PM

Just for remarks.....  the "Font" must be in pixel Uom otherwise the MeasureString returns a strange value!....  

Jul 14, 2010 at 10:46 AM

(x2-x1)/2, (y2-y1)/2