Reputation: 55
I have a string with text and I want to output it centering on specific character position.
Is there a way to do so using, for example, label?
Or should I better consider drawing a string using GDI+ measuring each character length and then manually drawing it where I need, centered?
Example, to be clearer:
String: "Lorem Ipsum", Position: 2.
From this, I need the string displayed in such way that character "r" will be in the middle of whatever display box (label, etc.).
Upvotes: 1
Views: 382
Reputation: 54433
Here is a positioning function that should help:
void positionTo(Label lbl, Panel pan, int pos)
{
SizeF sz0, sz1, sz2;
sz0 = sz1 = sz2 = Size.Empty;
using (Graphics g = lbl.CreateGraphics())
{
StringFormat sf = StringFormat.GenericTypographic;
sz0 = g.MeasureString(lbl.Text, lbl.Font, pan.Width, sf);
sz1 = g.MeasureString(lbl.Text.Substring(0, pos), lbl.Font, pan.Width, sf);
sz2 = g.MeasureString(lbl.Text.Substring(pos), lbl.Font, pan.Width, sf);
}
lbl.Left = (int)(pan.Width / 2 - sz1.Width);
}
Note that I use only the left part measurement. One could use both to refine the centering..
Upvotes: 3