You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何将图片按固定大小自适应显示在DataGridView图片列中

问题描述

我用DataGridView展示员工数据,其中有一列用来显示员工状态,使用的是两张48×48的图片(Status_Active和Status_Inactive)。我希望这列的图片能以固定大小(比如16×16或32×32)显示,但实际显示时图片总是被放大。我尝试把ImageLayout设置为Center,也没达到预期效果。

目前我从数据库获取员工列表,循环为每个员工添加行数据和对应的状态图标,但状态图标显示尺寸远大于期望的固定大小。

我的实现代码:

var employees = db.Employees.ToList();
// Add a row for each employee
foreach (var employee in employees)
{
    using (Image statusIcon = employee.IsActive ? Resources.Status_Active : Resources.Status_Inactive)
    {
        string fullName = employee.LastName + ", " + employee.FirstName;
        dgvStatustableau.Rows.Add(fullName, statusIcon);
    }
}
解决方案

感谢@IVSoftware提供的有效方案,通过创建指定尺寸的位图来重新绘制图标,解决了图片显示过大的问题。实现代码如下:

Bitmap resizedIcon = new Bitmap(16, 16);
using (Graphics g = Graphics.FromImage(resizedIcon))
{
    g.DrawImage(statusIcon, new Rectangle(0, 0, 16, 16));
}

内容的提问来源于stack exchange,提问作者Ḥakim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 14:48:22