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

如何在C# Windows Forms中随画布分辨率正确缩放像素艺术图像且不模糊

核心修改点

默认GDI+的缩放采用双线性插值算法,会对边缘做平滑处理,导致像素艺术出现模糊。你需要调整Graphics对象的渲染配置,适配像素风格的渲染需求:

  • 将插值模式设置为最近邻插值,避免缩放时的像素平滑运算
  • 调整像素偏移模式,解决最近邻采样导致的像素错位问题
  • 关闭抗锯齿,保留像素艺术的硬边缘特性

优化后完整代码

using System.Drawing.Drawing2D; // 需提前引入该命名空间

public void PictureBox_Paint(object sender, PaintEventArgs e)
{
    var graphics = e.Graphics;
    // 像素艺术专属渲染配置
    graphics.InterpolationMode = InterpolationMode.NearestNeighbor;
    graphics.PixelOffsetMode = PixelOffsetMode.Half;
    graphics.SmoothingMode = SmoothingMode.None;
    
    graphics.MultiplyTransform(ScaleMatrix());
    
    // 此处保留你原有绘制图像的逻辑即可
}

public float VirtualWidth = 1024;
public float VirtualHeight = 768;

public Matrix ScaleMatrix()
{
    var matrix = new Matrix();

    // 若需保持原图像宽高比不被拉伸,可替换为等比例缩放逻辑:
    // float scale = Math.Min((float)PictureBox.Width / VirtualWidth, (float)PictureBox.Height / VirtualHeight);
    // float x = scale, y = scale;
    var x = (float) this.PictureBox.Width / VirtualWidth;
    var y = (float) this.PictureBox.Height / VirtualHeight;

    matrix.Scale(x, y);

    return matrix;
}

可选适配项

如果不需要图像拉伸填满整个PictureBox,只需在ScaleMatrix中完成等比例缩放后,额外添加平移变换,将缩放后的图像在PictureBox中居中显示即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:54:02