[英]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種可能的值,並且單元格看起來相同:
他們都不符合我的意願。 官方文檔在這里 。 我想要與Forms.ImageLayout.Zoom相同的行為。
注意:我使用.NET Framework v4.6.1。
我通過添加以下行解決了該問題:
IconColumn.ImageLayout = DataGridViewImageCellLayout.Zoom;
在每個語句之后添加或更新DataGridView中的圖標。
似乎將此屬性設置為與以前相同的值會按照該屬性的值建議的方式重新繪制列中的圖標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.