日期:2014-05-17  浏览次数:20932 次

【分享】自己做了一个画直线的自定义控件
由于自己写着玩的一个项目需要自己动手写了一个简单的画直线的控件
1:可以修改颜色,宽度,
2:通过起始点和终点来任意画线,
3:并且简单的通过比较斜率实现了判断是否鼠标选择了线。
比较粗糙欢迎指正。
运行图如下:

http://img.my.csdn.net/uploads/201208/24/1345780226_8579.jpg
http://img.my.csdn.net/uploads/201208/24/1345780364_6103.jpg
代码如下:
C# code

public partial class UserLine : UserControl
    {
        private Point lineStart;
        private Point lineEnd;
        private int lineWidth;
        private Color lineColor;
        private Pen pen;

        public UserLine()
        {
            InitializeComponent();
        }
        public Point LineStart
        {
            get
            {
                return lineStart;
            }
            set
            {
                this.lineStart=new Point(value.X,value.Y);
            }
        }
        public Point LineEnd
        {
            get
            {
                return lineEnd;
            }
            set
            {
                this.lineEnd = new Point(value.X, value.Y);
            }
        }
        public int LineWidth
        {
            get
            {
                return lineWidth;
            }
            set
            {
                this.lineWidth = value;
            }
        }
        public Color  LineColor
        {
            get
            {
                return lineColor;
            }
            set
            {
                this.lineColor = value;
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            pen=new Pen(LineColor,LineWidth);
            base.OnPaint(e);
            e.Graphics.DrawLine(pen,LineStart,LineEnd);
        }
        int i = 0;
        private void UserLine_MouseDown(object sender, MouseEventArgs e)
        {
            if (((e.Y - lineStart.X) / (e.X - lineStart.X)) == ((lineEnd.Y - lineStart.Y) / (lineEnd.X - lineStart.X)))
            {
                if (e.Button == MouseButtons.Left)
                {
                    i++;
                    if (i == 2)
                    {
                        this.LineColor = Color.Red;
                        this.LineWidth = 6;
                        i = 0;
                    }
                    else
                        this.LineColor = Color.Yellow;
                }
            }
            this.Invalidate();
        }
        
    }




------解决方案--------------------
楼主,支持一下,不过希望你不要再舍易求难了!