65.9K
CodeProject 正在变化。 阅读更多。
Home

PixelBox:一个具有可配置插值模式的 PictureBox

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.83/5 (16投票s)

2014年1月28日

CPOL

2分钟阅读

viewsIcon

33729

downloadIcon

1083

标准的 Windows Forms PictureBox 缺少一个非常有用的代码行。

介绍 

我们并不经常处理极低分辨率或像素化的图像,但当我们处理时,我们可能对图像的外观有不同的期望。

在一个最近的项目中,我希望显示图像的像素化效果,但当在默认的 PictureBox 中显示时,像素化效果无法看到,因为该控件正在平滑像素化。

我想要的效果(InterpolationType.NearestNeighbor):

 

我得到的效果(InterpolationType.Default):



背景 

Windows.Forms.Controls.PictureBox 是 Windows Forms 应用程序中用于显示图像的标准控件。它在这方面做得不错,并提供了一些自定义选项,例如 SizeMode,以设置图像如何适应框。

当以任何不同于图像原始大小的尺寸显示图像时,即像素到像素,用于将低分辨率图像转换为高分辨率图像,反之亦然的额外像素必须来自某个地方。 这称为**插值**,事实证明有很多算法可以完成此操作。

PixelBox 是从 PictureBox 派生的自定义控件。 它添加了 InterpolationMode 属性,该属性的效果是在将图像绘制到控件的表面之前设置 GDI+ 插值模式。 该属性是 InterpolationMode 枚举 中的一个值。

代码

PictureBox 的更改非常简单。 整个类如下所示:

using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
 
namespace RedCell.UI.Controls
{
    /// <summary>
    /// A PictureBox with configurable interpolation mode.
    /// </summary>
    public class PixelBox : PictureBox
    {
        #region Initialization
        /// <summary>
        /// Initializes a new instance of the <see cref="PixelBox"> class.
        /// </see></summary>
        public PixelBox ()
        {
            // Set default.
            InterpolationMode = InterpolationMode.Default;
        }
        #endregion
 
        #region Properties
        /// <summary>
        /// Gets or sets the interpolation mode.
        /// </summary>
        /// <value>The interpolation mode.</value>
        [Category("Behavior")]
        [DefaultValue(InterpolationMode.Default)]
        public InterpolationMode InterpolationMode { get; set; }
        #endregion
 
        #region Overrides of PictureBox
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Control.Paint"> event.
        /// </see></summary>
        /// <param name="pe" />A <see cref="T:System.Windows.Forms.PaintEventArgs"> that contains the event data. 
        protected override void OnPaint (PaintEventArgs pe)
        {
            pe.Graphics.InterpolationMode = InterpolationMode;
            base.OnPaint(pe);
        }
        #endregion
    }
}
</see>

演示

演示应用程序演示了像素化图像上的任何插值模式。 除了上面显示的模式之外,这里还有其他模式用于比较

InterpolationMode.Low 

InterpolationMode.High 

InterpolationMode.Bilinear

InterpolationMode.Bicubic

InterpolationMode.HighQualityBilinear

InterpolationMode.HighQualityBicubic

结论

通过子类化 PictureBox 并重写其 OnPaint 方法,我们可以设置 GDI+ InterpolationMode 属性,从而使我们能够更好地控制渲染的算法、质量和速度。

历史

2014年1月28日

首次发布。

© . All rights reserved.