如何用C#绘制流畅的图像?

我正在尝试在C#表单上绘制图像(在PictureBoxes中,以及使用Graphics.DrawImage()),并且正在寻找一种平滑绘制它们的方法。 图像必须是支持透明度的格式,因此PNG,GIF,SVG和WMF。 C#不支持开箱即用的SVG文件,我还没有找到一个好的第三方库(我找到了SvgNet,但无法弄明白)。

我需要绘制一个WMF文件,C#可以通过Image.FromFile()函数来完成,但它没有消除锯齿。 我想知道是否有办法解决这个问题?

之前的答案虽然很有意,但只是部分正确。

什么是正确的? PictureBox不会公开InterpolationMode。

什么是基地?

1)虽然您可以从图片框,父图标或派生类中的覆盖中轻松地在Paint事件中设置该属性。 。 。 无论哪种方式都有效,两者都同样容易。 但是,除非设置了SmoothingMode,否则将忽略InterpolationMode。 如果没有将SmoothingMode设置为SmoothingMode.AnitAlias,您将不会获得任何抗锯齿。

2)当你明确表示有兴趣使用PictureBox的function时使用Panel是错误的方向。 如果没有明确编码这些属性,您将无法直接加载,保存或分配图像。 。 。 为什么重新发明轮子? 通过派生PictureBox,您可以免费获得所有这些。

因为我已经为你完成了艰苦的工作 ,这个消息变得更好了,这比写这个消息花了我更少的时间。

我提供了两个版本,这两个版本都派生自PictureBox。 首先是一个简单的例子,它总是使用最好的质量渲染。 这也是最慢的渲染。 第二个是允许任何人通过派生类的属性设置各种渲染参数的类。 设置后,这些将在OnPaint覆盖中使用。

public class HighQualitySmoothPictureBox : PictureBox { protected override void OnPaint(PaintEventArgs pe) { // This is the only line needed for anti-aliasing to be turned on. pe.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; // the next two lines of code (not comments) are needed to get the highest // possible quiality of anti-aliasing. Remove them if you want the image to render faster. pe.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; pe.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // this line is needed for .net to draw the contents. base.OnPaint(pe); } } 

 public class ConfigurableQualityPictureBox : PictureBox { // Note: the use of the "?" indicates the value type is "nullable." // If the property is unset, it doesn't have a value, and therefore isn't // used when the OnPaint method executes. System.Drawing.Drawing2D.SmoothingMode? smoothingMode; System.Drawing.Drawing2D.CompositingQuality? compositingQuality; System.Drawing.Drawing2D.InterpolationMode? interpolationMode; public System.Drawing.Drawing2D.SmoothingMode? SmoothingMode { get { return smoothingMode; } set { smoothingMode = value; } } public System.Drawing.Drawing2D.CompositingQuality? CompositingQuality { get { return compositingQuality; } set { compositingQuality = value; } } public System.Drawing.Drawing2D.InterpolationMode? InterpolationMode { get { return interpolationMode; } set { interpolationMode = value; } } protected override void OnPaint(PaintEventArgs pe) { if (smoothingMode.HasValue) pe.Graphics.SmoothingMode = smoothingMode.Value; if (compositingQuality.HasValue) pe.Graphics.CompositingQuality = compositingQuality.Value; if (interpolationMode.HasValue) pe.Graphics.InterpolationMode = interpolationMode.Value; // this line is needed for .net to draw the contents. base.OnPaint(pe); } } 

将图像绘制到canvas时,可以将插值模式更改为比最近邻居更好的值,以使resize的图像平滑:

 Graphics g = ... g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(...); 

您需要添加System.Drawing.Drawing2D以获取InterpolationMode枚举。

使用PictureBox将是一个问题 – 它不会公开InterpolationMode属性,因此您需要自己滚动或下载一个。