Determining the position of a string after drawing it with WinForms (C #)
I am drawing a string within a large bounding box and using StringFormat to align the string appropriately. However, I need the actual (X, Y) location of the string after drawing it (not just the size given by MeasureString).
I am using the following code:
CharacterRange[] ranges = { new CharacterRange(0, this.Text.Length) };
format.SetMeasurableCharacterRanges(ranges);
//Measure character range
Region[] region = g.MeasureCharacterRanges(this.Text, this.Font, layoutRect, format);
RectangleF boundsF = region[0].GetBounds(g);
bounds = new Rectangle((int)boundsF.Left, (int)boundsF.Top,
(int)boundsF.Width, (int)boundsF.Height);
This is a code segment, so ignore any missing declarations. The point is that the rectangle indicated by the above code is not the correct size, the last character of the line is discarded and only the first line of lines is drawn.
Does anyone know why, or maybe a better way to do this?
thanks
Make sure you are using the correct format to measure your text. You haven't included all of the source code, so I can't tell if you have.
There are two standard format values that you can use:
StringFormat.GenericTypographic
and StringFormat.GenericDefault
. If you are using the memory selected by default, as a rule, GenericDefault
but the one you want with the visualization interface GenericTypographic
.
So instead of doing, new StringFormat()
you want to do StringFormat.GenericTypographic.Clone()
. This should correct margins / spacing and give measurement results that match those shown on the surface Graphics
.
The strategy I usually use is to build a single instance StringFormat
and use it for both rendering text and measuring to make sure everything is ok: I avoid any method that allows me to omit StringFormat
, since by default, probably what I want.
Hope this helps. If you still have problems, please try posting a more complete code snippet so we can see how you draw your text.
a source to share
Using:
TextBox tb = new TextBox { Text = "Test", Multiline = true };
Size size = System.Windows.Forms.TextRenderer.MeasureText(tb.Text, tb.Font);
Point location = new Point( //Is this what you were looking for?
tb.Location.X + size.Width,
tb.Location.Y + size.Height);
Note that there are additional overloads for this method, please check.
a source to share