Home > Software engineering >  Circular Hitbox in Visual Basic WinForm
Circular Hitbox in Visual Basic WinForm

Time:03-08

How can I change the hitbox of a PictureBox where the image is circular? By hitbox, I mean where the ClickEvent registers.

CodePudding user response:

You can use the Control.Region property, to create a Region using a circular GraphicsPath. This Region is used for the Click event, as well as the MouseEnter, MouseHover, and MouseLeave events.

Example with a PictureBox:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim path As New Drawing2D.GraphicsPath()
        path.AddArc(0, 0, PictureBox1.Width, PictureBox1.Height, 0, 360) 'A circle at 0,0 relative to the PictureBox, sharing its Width and Height
        PictureBox1.Region = New Region(path)
End Sub

CodePudding user response:

If you want a circle in the middle (instead of an oval), then use something like:

Dim path As New Drawing2D.GraphicsPath()
Dim radius As Integer = Math.Min(PictureBox1.Width - 1, PictureBox1.Height - 1) / 2
Dim rc As New Rectangle(New Point(PictureBox1.Width / 2, PictureBox1.Height / 2), New Size(1, 1))
rc.Inflate(radius, radius)
path.AddEllipse(rc)
PictureBox1.Region = New Region(path)
  • Related