我正在使用Winforms中的小图表程序。我目前能够创建一个矩形数组,但我不知道如何通过鼠标单击实现它们,并能够显示每个矩形的属性(即名称)。
这就是我现在所拥有的。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NodeGraph
{
public partial class NodeGraphPanel : UserControl
{
Point cursorPoint;
Rectangle[] NodeRectange = new Rectangle[1];
public string name;
int id = 0;
public NodeGraphPanel()
{
InitializeComponent();
}
public void DrawText()
{
cursorPoint = PointToClient(Cursor.Position);
for(int i = 0; i < NodeRectange.Length; i++)
{
NodeRectange[i] = new Rectangle();
NodeRectange[i].Size = new Size(200, 100);
NodeRectange[i].Location = cursorPoint;
name = "NodeRectange" + id;
id++;
Pen pen = new Pen(Color.Black, 2);
pen.Alignment = PenAlignment.Center;
Graphics g;
g = this.CreateGraphics();
SolidBrush myBrush = new SolidBrush(Color.FromArgb(0, 174, 219));
SolidBrush myBrush2 = new SolidBrush(Color.FromArgb(85, 85, 85));
using (Font font1 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point))
{
g.DrawString(name, font1, Brushes.Black, NodeRectange[i].X,NodeRectange[i].Y);
g.DrawRectangle(pen, NodeRectange[i]);
g.FillRectangle(myBrush, NodeRectange[i]);
g.FillRectangle(myBrush2, new Rectangle(cursorPoint.X, cursorPoint.Y, 200, 30));
g.Dispose();
myBrush.Dispose();
}
label1.Text = name;
}
}
}
}
我尝试了显示的Line示例并且它有效。但我将其更改为Rectangle类并重新创建它以适合Rectangle方法。在跑步时我没有任何错误,但它没有画画。 这是代码:
class Rectangle
{
public Point LocX { get; set; }
public Point LocY { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public Rectangle(Point x, Point y, int v1, int v2)
{
LocX = x; LocY = y; Width = v1; Height = v2;
}
public void Draw(Graphics G)
{ using (Brush brush = new SolidBrush(Color.AliceBlue)) G.FillRectangle(brush, LocX.X,LocY.Y,Width,Height); }
}
这就是我用它来运行它:
List<Rectangle> rectangles = new List<Rectangle>();
rectangles.Add(new Rectangle(new Point(cursorPoint.X), new Point(cursorPoint.Y),100,50));