我通过保留起点和终点创建了一条线。目前,如果我想移动起点或终点,我必须单击某个点来移动一个点。
但有时我不想改变起点和终点的距离。所以我想点击两点之间的一条线来移动一条线和移动线的位置。
如何使线条成为对象?如果用户点击该行,该如何处理?
下面是一个画线的类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
namespace BaseClasses
{
public class MyLine : Control
{
private int _lineSize = 1;
[DefaultValue(typeof(int), "1")]
public int LineSize
{
get
{
return _lineSize;
}
set
{
if (value != _lineSize)
{
_lineSize = value;
MinimumSize = new Size(_lineSize, _lineSize);
if (Parent != null)
Invalidate();
}
}
}
private LineOrientation _orientation = LineOrientation.Diag1;
[DefaultValue(typeof(LineOrientation), "Diag1")]
public LineOrientation Orientation
{
get
{
return _orientation;
}
set
{
if (value != _orientation)
{
_orientation = value;
if (Parent != null)
Invalidate();
}
}
}
private Color _lineColor = Color.Black;
[DefaultValue(typeof(Color), "Black")]
public Color LineColor
{
get
{
return _lineColor;
}
set
{
if (value != _lineColor)
{
_lineColor = value;
if (Parent != null)
Invalidate();
}
}
}
public MyLine()
{
TabStop = false;
}
protected override void OnParentChanged(EventArgs e)
{
base.OnParentChanged(e);
if (Parent != null)
this.BackColor = this.Parent.BackColor;
}
protected override void OnParentBackColorChanged(EventArgs e)
{
base.OnParentBackColorChanged(e);
this.BackColor = this.Parent.BackColor;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (Pen pen = new Pen(_lineColor, _lineSize))
{
if (_orientation == LineOrientation.Diag1)
e.Graphics.DrawLine(pen, _lineSize - 1, _lineSize - 1, Width - _lineSize, Height - _lineSize);
else if (_orientation == LineOrientation.Diag2)
e.Graphics.DrawLine(pen, _lineSize - 1, Height - _lineSize, Width - _lineSize, _lineSize - 1);
else if (_orientation == LineOrientation.Horiz)
e.Graphics.DrawLine(pen, _lineSize - 1, (Height - _lineSize) / 2, Width - _lineSize, (Height - _lineSize) / 2);
else if (_orientation == LineOrientation.Vert)
e.Graphics.DrawLine(pen, (Width - _lineSize) / 2, Height - _lineSize, (Width - _lineSize) / 2, _lineSize - 1);
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Invalidate();
}
}
public enum LineOrientation { Diag1, Diag2, Vert, Horiz }
}
点击事件应该在基类级别(Control(处理,并确定点击是发生在行上还是其他地方。