简体   繁体   中英

Automatically resize font size of DataGridView cell text?

I have a DataGridView that I use as sort of a graphic for a 2D array.

在此处输入图片说明

My issue is that I cannot figure out how, or if it is possible, to automatically scale the text in the cells to the size of the cell.

I have found this SO answer which shows how to change the font of the cell itself, though if I were to take this approach I would have to calculate the proper font size of the text to fit the cell manually. Which is just not worth the effort.

I would have to assume there is a setting in DataGridView to have it automatically scale the cell font size? I cannot seem to find it.

As far as I know, automatic scaling does not exist in Windows forms.

By the way, this could help you :

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if ((e.PaintParts & DataGridViewPaintParts.ContentForeground) != 0 && e.FormattedValue != null && e.FormattedValue.ToString().Length > 0
        && e.RowIndex >= 0 && e.ColumnIndex >= 0)
    {
        var cellText = e.FormattedValue.ToString();
        for (var fontSize = 8; fontSize <= 72; fontSize++)
        {
            var font = new Font(e.CellStyle.Font.FontFamily, fontSize, e.CellStyle.Font.Style);
            var textSize = TextRenderer.MeasureText(cellText, font);
            //var textSize = e.Graphics.MeasureString(cellText, font); 
            if (textSize.Width > e.CellBounds.Width || textSize.Height > e.CellBounds.Height)
            {
                font = new Font(e.CellStyle.Font.FontFamily, fontSize - 1, e.CellStyle.Font.Style);
                e.CellStyle.Font = font;
                e.Paint(e.ClipBounds, e.PaintParts);
                e.Handled = true;
                break;
            }
        }
    }

To chose which measuring string method to use, please consult these links :

I also suggest you to optimize it with a Font dictionary, to avoid multiple Font instance creation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM