[转]鼠标移到图像上显示激活的例子

原文作者 java_liyic#+Gdi,怎么移动和改变已经绘制好的图形位置和大小

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DrawTest
{
    public delegate void DrawMeHandler(Graphics g);
    public delegate void MouseMoveHandler(Point p);
    public partial class Canvas : UserControl
    {
        RectangleFigure rectangleFigure = new RectangleFigure();
        DrawMeHandler drawMeHandler;
        MouseMoveHandler mouseMoveHandler;
        public Canvas()
        {
            InitializeComponent();
            this.DoubleBuffered = true;
            this.Paint += Canvas_Paint;
            this.Load += Canvas_Load;
            this.MouseMove += Canvas_MouseMove;
        }

        void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            this.mouseMoveHandler.Invoke(e.Location);
            this.Refresh();
        }

        void Canvas_Load(object sender, EventArgs e)
        {
            rectangleFigure.X = 10;
            rectangleFigure.Y = 10;
            rectangleFigure.Width = 100;
            rectangleFigure.Height = 50;
            drawMeHandler = new DrawMeHandler(rectangleFigure.DrawMe);
            mouseMoveHandler = new MouseMoveHandler(rectangleFigure.MouseMove);
            
        }

        void Canvas_Paint(object sender, PaintEventArgs e)
        {
            if (drawMeHandler != null) drawMeHandler.Invoke(e.Graphics);
        }


        /// <summary>
        /// 矩形对象
        /// </summary>
        public class RectangleFigure
        {
            
            public int X { get; set; }
            public int Y { get; set; }
            public int Height { get; set; }
            public int Width { get; set; }

            public bool Actived { get; set; }

            public bool IsExist(Point p)
            {
                Rectangle rectangle = new Rectangle(this.X, this.Y, this.Width, this.Height);
                return rectangle.Contains(p);
            }

            public void MouseMove(Point p)
            {
                Actived = IsExist(p);
            }

            public void DrawMe(Graphics g)
            {
                Pen p = new Pen(Color.Black);
                g.FillRectangle(p.Brush, this.X, this.Y, this.Width, this.Height);
                if (Actived)
                {
                    p.Color = Color.Red;
                    g.DrawRectangle(p, this.X, this.Y, this.Width, this.Height);
                }
            }
        }
    }
}

 

posted @ 2016-08-26 16:09  wenglabs  阅读(308)  评论(0编辑  收藏  举报