How to create a clickable irregularly-shaped region in c#

前端 未结 3 1907
眼角桃花
眼角桃花 2020-12-10 16:59

I have an irregularly-shaped picture like a heart or any random shape. I can make it transparent visually, but I need to make it clickable only on the shape area. I heard th

3条回答
  •  鱼传尺愫
    2020-12-10 17:46

    Here is a Winforms example of handling an image mask. When the user clicks on the mask image it pops up a message box. This basic technique can obviously be modified to suit.

    public partial class Form1 : Form {
        readonly Color mask = Color.Black;
        public Form1() {
            InitializeComponent();
        }
    
        private void pictureBox1_Click(object sender, EventArgs e) {
            var me = e as MouseEventArgs;
            using (var bmp = new Bitmap(pictureBox1.Image)) {
                if (me.X < pictureBox1.Image.Width && me.Y < pictureBox1.Image.Height) {
                    var colorAtMouse = bmp.GetPixel(me.X, me.Y);
                    if (colorAtMouse.ToArgb() == mask.ToArgb()) {
                        MessageBox.Show("Mask clicked!");
                    }
                }
            }
        }
    }
    

    pictureBox1 has an Image loaded from a resource of a heart shape that I free-handed.

提交回复
热议问题