【问题标题】:Automatically resize font size of DataGridView cell text?自动调整 DataGridView 单元格文本的字体大小?
【发布时间】:2016-02-19 16:35:59
【问题描述】:

我有一个DataGridView,用作二维数组的图形。

我的问题是我无法弄清楚如何或是否可以将单元格中的文本自动缩放到单元格的大小。

我发现了这个SO answer,它显示了如何更改单元格本身的字体,但如果我采用这种方法,我必须手动计算文本的正确字体大小以适应单元格。这是不值得的。

我必须假设 DataGridView 中有一个设置可以自动缩放单元格字体大小?我似乎找不到它。

【问题讨论】:

  • 很遗憾,DataGridView 中不存在自动缩放。

标签: c# datagridview


【解决方案1】:

据我所知,Windows 窗体中不存在自动缩放。

顺便说一句,这可以帮助你:

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;
            }
        }
    }

要选择使用哪种测量字符串方法,请参考以下链接:

我还建议您使用Font 字典对其进行优化,以避免创建多个Font 实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    相关资源
    最近更新 更多