我试图在窗体中绘制不同形状,就像我们在绘画中绘制一样。 我想要的场景就像当用户点击矩形按钮然后在表格上绘制一个矩形时应该绘制,因此绘制手绘形状的情况也是如此。以下是我的代码:
{
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);
我面临两个问题;首先是我能够向前绘制我的矩形,但是当我尝试向后绘制它时它不起作用。 其次,当我点击手绘按钮然后它在绘图上绘制为徒手形状,但当我第一次点击矩形按钮,然后单击徒手按钮时,它不会绘制任何手绘形状。 我是初学者,所以要温柔,请帮助我:)
答案 0 :(得分:0)
不要将initialX和initialY作为nstarting坐标发送 而是发送:
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));