在文本方面的DataGridView标题中绘制图像

时间:2015-05-28 18:38:16

标签: c# image winforms datagridview

我正在尝试在文本方面的DataGridView标题中绘制图像。我可以绘制图像,但它失去了分辨率。为什么呢?

之前:

enter image description here

之后(在DataGridView标题上):

enter image description here

我试图调整它的大小,但它没有区别。此外,我想保留标题的文本并将图像放在文本的右侧。我该怎么做?

我正在做以下事情:

   private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex == 0 && e.RowIndex == -1)
            {

                // original image size is 96x96 px
                Image img = ScaleImage(imageList1.Images[0], 32, 32);
                var s = e.CellBounds;
                s.Height = img.Height;
                s.Width = img.Width;
                e.Paint(s, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentForeground);
                e.Graphics.DrawImage(img, s);
                e.Handled = true;
            }
        }


    //code taken from: http://stackoverflow.com/questions/6501797/resize-image-proportionally-with-maxheight-and-maxwidth-constraints
    // all credits to @Alex Aza
    public Image ScaleImage(Image image, int maxWidth, int maxHeight)
    {
        var ratioX = (double)maxWidth / image.Width;
        var ratioY = (double)maxHeight / image.Height;
        var ratio = Math.Min(ratioX, ratioY);

        var newWidth = (int)(image.Width * ratio);
        var newHeight = (int)(image.Height * ratio);

        var newImage = new Bitmap(newWidth, newHeight);
        Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
        return newImage;
    }

所以我的问题是:如何绘制图像以使其不会丢失分辨率并保留标题的文本?

2 个答案:

答案 0 :(得分:2)

您可以对DataGridView DGV

使用类似的内容

enter image description here

private void DGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex == yourColumn && e.RowIndex == -1)
    {
       DGV.ColumnHeadersHeight = 32;  // or maybe a little more..
       // should be prepared, maybe in an imagelist!!
       Image img = Image.FromFile("D:\\dollars96.png");
       Rectangle r32 = new Rectangle(e.CellBounds.Left + e.CellBounds.Width - 32, 0, 32,32);
       Rectangle r96 = new Rectangle(0, 0, 96,96);
       string header = DGV.Columns[e.ColumnIndex].HeaderText;
       e.PaintBackground(e.CellBounds, true);  // or maybe false ie no selection?
       e.PaintContent(e.CellBounds);  

       e.Graphics.DrawImage(img, r32, r96, GraphicsUnit.Pixel);

       e.Handled = true;
    }
    // any other cell: let the system do its thing
    else e.Handled = false;
}

您可能想要检查ImageList的设置;默认值相当低质量!你可以在那里将它们设置为32x32,顺便说一句。升级ColorDepth

答案 1 :(得分:0)

我猜测DataGridViewImageColumn的ImageLayout属性设置错误。