如何在窗体中制作不同的形状,就像我们在油漆中绘制一样
本文关键字:我们 绘制 一样 窗体 | 更新日期: 2023-09-27 18:10:39
我正在尝试在窗口形式中绘制不同的形状,就像我们在油漆中绘制一样。我想要的场景,当用户单击矩形按钮,然后在窗体上绘制一个矩形,它应该绘制,所以是绘制手绘形状的情况。下面是我的代码:
{
bool shouldPaint = false;
int initialX;
int initialY;
bool rectButton = false;
bool freeButton = false;
public Form1()
{
InitializeComponent();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
shouldPaint = true;
initialX = e.X;
initialY = e.Y;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
shouldPaint = false;
}
if ( (rectButton==true) && (shouldPaint))
{
//
this.Invalidate();
this.Refresh();
System.Drawing.Pen pen1 = new System.Drawing.Pen(System.Drawing.Color.Black);
Graphics painter = CreateGraphics();
int width = e.X - initialX, height = e.Y - initialY;
Rectangle rect = new Rectangle(initialX, initialY, width * Math.Sign(width), height * Math.Sign(height));
painter.DrawRectangle(pen1, rect);
}
else if ((freeButton == true) && (shouldPaint))
{
//this.Refresh();
// this.Invalidate();
Graphics painter = CreateGraphics();
painter.FillEllipse(new SolidBrush(Color.Black), e.X, e.Y, 4, 4);
我面临两个问题;第一个是,我可以在正方向上画我的矩形,但当我试着在反方向上画它时,它不起作用。其次,当我点击手绘按钮时,它会在窗体上绘制手绘形状,但当我先点击矩形按钮,然后点击手绘按钮时,它不会绘制任何手绘形状。我是初学者,所以请温柔地帮助我:)
不发送initialX和initialY作为起始坐标而是发送:
int minX = Math.Min((int)initX, (int)e.X);
int minY = Math.Min((int)initY, (int)e.Y);
Rectangle rect = new Rectangle(minX,minY width * Math.Sign(width), height * Math.Sign(height));