Disable Image blending on a PictureBox

前端 未结 2 1752
无人及你
无人及你 2020-12-06 14:39

In my Windows Forms program, I have a PictureBox. The bitmap image inside it is small, 5 x 5 pixels.
When assigned to a PictureBox

2条回答
  •  有刺的猬
    2020-12-06 14:51

    A solution I've seen around a couple of times is to make an overriding class of PictureBox which has the InterpolationMode as class property. Then all you need to do is use this class on the UI instead of .Net's own PictureBox, and set that mode to NearestNeighbor.

    Public Class PixelBox
        Inherits PictureBox
    
        
        
        Public Property InterpolationMode As InterpolationMode = InterpolationMode.NearestNeighbor
    
        Protected Overrides Sub OnPaint(pe As PaintEventArgs)
            Dim g As Graphics = pe.Graphics
            g.InterpolationMode = Me.InterpolationMode
            ' Fix half-pixel shift on NearestNeighbor
            If Me.InterpolationMode = InterpolationMode.NearestNeighbor Then _
                g.PixelOffsetMode = PixelOffsetMode.Half
            MyBase.OnPaint(pe)
        End Sub
    End Class
    

    As was remarked in the comments, for Nearest Neighbor mode, you need to set the PixelOffsetMode to Half. I honestly don't understand why they bothered exposing that rather than making it an automatic choice inside the internal rendering process.

    The size can be controlled by setting the control's SizeMode property. Putting it to Zoom will make it automatically center and expand without clipping in the control's set size.

提交回复
热议问题