Search code examples
c#.netvb.netgdi+clipping

Graphics FillRectangle except Specified Area (.NET, GDI+)


I would like to use Graphics.FillRectangle or Graphics.Clear with semi-transparent colour (e.g. ARGB=128,0,0,0) to darken entire area of the Graphics object except some specified (rectangular) area:

enter image description here

I know this can be achieved with four FillRectangle calls, but I wonder if it cannot be done easier.

I am aware of simple clipping (Graphics.SetClip), but this allows me to clip everything outside the specified area and I would like to achieve the opposite.


Solution

  • Dim img = Bitmap.FromFile("C:\Users\Public\Pictures\Sample Pictures\Desert.jpg")
    
    Using gfx = Graphics.FromImage(img)
        Dim r = New Rectangle(100, 150, 50, 50)
        gfx.SetClip(r, Drawing2D.CombineMode.Exclude)
        Using b = New SolidBrush(Color.FromArgb(128, 0, 0, 0))
            gfx.FillRectangle(b, New Rectangle(0, 0, img.Width, img.Height))
        End Using
        Me.PictureBox1.Image = img
    End Using