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

C#中如何调整图片及内部绘制矩形的大小并保持矩形位置

解决C#中图片缩放后保持矩形位置与比例的问题

你的代码问题出在缩放逻辑错误——直接给坐标和尺寸加20%的方式,没法保证矩形和图片的相对位置一致。正确的做法是用统一的缩放因子,对图片尺寸、矩形的坐标和宽高做等比例计算,同时要避免临时绘制导致的重绘丢失问题。

核心修正点:

  • 定义统一的缩放因子(比如放大20%就是scaleFactor = 1.2f)
  • 图片新尺寸 = 原尺寸 × 缩放因子
  • 矩形的X、Y、Width、Height都要 × 缩放因子,确保相对位置不变
  • 在PictureBox的Paint事件中绘制矩形,避免窗口重绘后矩形消失

修正后的代码示例:

int index3 = dataGridView1.CurrentCell.RowIndex;
// 读取原始矩形参数
int xxx = Convert.ToInt32(dataGridView1.Rows[index3].Cells[10].Value.ToString());
int yyy = Convert.ToInt32(dataGridView1.Rows[index3].Cells[11].Value.ToString());
int www = Convert.ToInt32(dataGridView1.Rows[index3].Cells[12].Value.ToString());
int hhh = Convert.ToInt32(dataGridView1.Rows[index3].Cells[13].Value.ToString());
Rectangle originalRect = new Rectangle(xxx, yyy, www, hhh);

// 定义缩放因子(放大20%,即1.2倍)
float scaleFactor = 1.2f;

// 计算图片新尺寸
int newPicWidth = (int)(picturModule.Width * scaleFactor);
int newPicHeight = (int)(picturModule.Height * scaleFactor);
picturModule.Size = new Size(newPicWidth, newPicHeight);

// 计算缩放后的矩形:所有参数乘以缩放因子
int newX = (int)(originalRect.X * scaleFactor);
int newY = (int)(originalRect.Y * scaleFactor);
int newWidth = (int)(originalRect.Width * scaleFactor);
int newHeight = (int)(originalRect.Height * scaleFactor);
Rectangle scaledRect = new Rectangle(newX, newY, newWidth, newHeight);

// 触发重绘,在Paint事件中绘制矩形(确保重绘不丢失)
picturModule.Invalidate();
picturModule.Paint += (sender, e) => {
    using (Pen pen = new Pen(Color.GreenYellow, 4))
    {
        e.Graphics.DrawRectangle(pen, scaledRect);
    }
};

额外说明:

  • 如果picturModule是显示图片的PictureBox,缩放控件时要把SizeMode设为StretchImage或Zoom,保证图片跟随控件缩放;如果是直接缩放图片文件,需要先对Image对象做缩放处理,再赋值给PictureBox的Image属性。
  • 用using包裹Pen对象,避免资源泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 07:35:20