的数据
我试图创建一个通过拖动鼠标,而被点击一个正方形,我可以单独创建squaure,但不能使它与预览工作。虽然它被拖动预览形状不被删除的某些原因,我真的不明白为什么会发生这种情况。我将包括图片和视频发生这种情况,因为它是有点难以解释它的文字。
Preview是如何工作的:有2笔,一个是用来擦除正在创建的形状,而光标通过形式旅行,直到它是让小康和广场的设计
public partial class Form1 : Form
{
Pen pen, eraser;
Graphics graphics;
Bitmap bitmap;
Point startPoint, endPoint;
int choice;
Boolean draw;
int width;
int height;
public Form1()
{
InitializeComponent();
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (draw && choice == 1)
{
width = e.Location.X - startPoint.X;
height = e.Location.Y - startPoint.Y;
width = height;
Rectangle shape = new Rectangle(startPoint.X, startPoint.Y, width, height);
graphics.DrawRectangle(pen, shape);
pictureBox1.Refresh();
draw = false;
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (draw && choice == 1)
{
width = e.Location.X - startPoint.X;
height = e.Location.Y - startPoint.Y;
width = height;
graphics.DrawRectangle(eraser, startPoint.X, startPoint.Y, width, height);
graphics.DrawRectangle(pen, startPoint.X, startPoint.Y, width, height);
pictureBox1.Refresh();
}
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
startPoint = e.Location;
draw = true;
}
字符串
1条答案
按热度按时间vktxenjb1#
您的代码采用了次优方法。当您想要在
PictureBox
上绘制时,您可以调用pictureBox1.Refresh()
* 或 * 您可以Invalidate
部分或全部ClientRectangle
。PictureBox
通过创建Graphics
上下文并触发Paint
事件来响应,从而为您提供可以绘制的机会和边界。需要注意的是,操作系统会告诉
PictureBox
在其他不同的时间进行重绘,而不一定是响应您的请求,例如当控件或其父控件调整大小时。如果您的绘图代码“在其他地方”,并且不包含在OnPaint
事件处理程序中,那么您在表面上绘制的任何内容都将被删除。你帖子中的图片证明了你的方法出了严重的问题。每次调用
Invalidate
时,你都会得到一个新的画布来绘制,如下所示。“擦除”任何东西都是完全不必要的,以至于如果你想保留以前绘制的方块,你必须将它们保存在某种文档中(参见下面的RectanglesToRedraw
)。的数据
字符串