簡體   English   中英

如何使用DataGridViewImageColumn通過縮放並保持寬高比顯示圖像?

[英]How to use DataGridViewImageColumn to display images using zoom and also keeping the aspect ratio?

我的密碼

建立專欄

IconColumn = new DataGridViewImageColumn()
{
    Name = "Icon",
    HeaderText = "Icon",
    SortMode = DataGridViewColumnSortMode.NotSortable,
    Width = 50,
    ImageLayout = DataGridViewImageCellLayout.Stretch,
    Resizable = DataGridViewTriState.False
};
IconColumn.DefaultCellStyle.NullValue = null;
IconColumn.CellTemplate = new ClockDataGridViewIconCell();

設置圖標

float maxHeight = 200;
float maxWidth = 200;

var r = new Rectangle(0,
    0,
    (int)Math.Round(maxWidth),
    (int)Math.Round(maxHeight)
);
MyClockData.Icon = Utils.ResizeToFitBoundingBox(
    new Bitmap(fd.FileName),
    r);

ResizeToFitBoundingBox方法

internal static Bitmap ResizeToFitBoundingBox(Image image, in Rectangle box)
{
    float maxHeight = box.Width;
    float maxWidth = box.Height;

    float x = Math.Min(maxWidth / image.Width,
        maxHeight / image.Height);

    float newW = (float)image.Width * x;
    float newH = (float)image.Height * x;

    var bmp = new Bitmap((int)Math.Round(maxWidth),
        (int)Math.Round(maxHeight));
    bmp.MakeTransparent();
    using (Graphics gr = Graphics.FromImage(bmp))
    {
        gr.DrawImage(image, (bmp.Width - newW) / 2,
            (bmp.Height - newH) / 2, newW, newH);
    }

    return bmp;
}

示例圖標

全尺寸的圖標

我已經嘗試了DataGridViewImageColumn.ImageLayout所有4種可能的值,並且單元格看起來相同:

  1. 正常

正常

  1. 沒有設置

沒有設置

  1. 伸展

伸展

  1. 放大

放大

他們都不符合我的意願。 官方文檔在這里 我想要與Forms.ImageLayout.Zoom相同的行為。

注意:我使用.NET Framework v4.6.1。

我通過添加以下行解決了該問題:

IconColumn.ImageLayout = DataGridViewImageCellLayout.Zoom;

在每個語句之后添加或更新DataGridView中的圖標。

似乎將此屬性設置為與以前相同的值會按照該屬性的值建議的方式重新繪制列中的圖標。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM