V
V
Volgarastraport2018-03-12 09:23:26
Mathematics
Volgarastraport, 2018-03-12 09:23:26

[C#] How to work with MeasureString in a loop?

I need to draw a list of headings with icons into an image.
5aa61b848dc87027993097.png
But since the headings have different lengths, either large gaps are obtained or the text is superimposed on each other.
I'm trying to keep the size of the previous block in the loop and shift the next one, but all the same, overlaps occur.
There are not many examples on the net, maybe someone here will tell you.

Bitmap bmp3 = null;
string str = "";
int step = (int) (s*0.2);
SizeF layoutSize = new SizeF((float)(w*0.5), (float)(s*0.2));
SizeF textSize = new SizeF();
for (int i = 0; i < list2.Count && i < 5; i++) {
  str = list2[i];
  textSize = grp.MeasureString(str, font, layoutSize);
  grp.DrawString(str, font, brush, new RectangleF(60, 20 + step, (int)(w*0.5)-50, step), stringFormat); //заголовок
  step = step + (int) textSize.Height;
  bmp3 = (Bitmap) Image.FromFile(list3[i], true); // иконка 
  grp.DrawImage(bmp3, 10, 25 + step, (int) (bmp3.Width * 0.25), (int) (bmp3.Height * 0.25));
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Ter, 2018-03-12
@Volgarastraport

You can try to calculate the number of rows:

private int GetNumOfLines(string multiPageString, int wrapWidth, Font fnt)
{
        var sfFmt = new StringFormat(StringFormatFlags.LineLimit);
        using(var g = Graphics.FromImage(New Bitmap(1, 1)))
       {
            var iHeight = g.MeasureString(multiPageString, fnt, wrapWidth, sfFmt).Height;
            var iOneLineHeight = g.MeasureString("Z", fnt, wrapWidth, sfFmt).Height;
            return (int)(iHeight / iOneLineHeight)
        }
}

And multiply by the font height

C
cicatrix, 2018-03-12
@cicatrix

Another hint: in simple cases, you can not call MeasureString, but use the Height property of the font itself.
From the example above, this is:
equivalent to this:
The question is still this - where do you draw all this? WPF, Winforms? The system window manager for these purposes itself can calculate everything. A Float Container with a length limit, and inside a Label set with Autosize, in principle, will save you from this torment.
Also keep in mind that MeasureString does not guarantee you accurate measurements of the text width. To calculate everything accurately, you need to use MeasureCharacterRanges

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question