我想在屏幕上动态绘制填充矩形,不透明度为0.1。问题是当我移动鼠标时,之前的矩形不清晰。
这是绘图方法。
private void OnMouseDown(object sender, MouseEventArgs e)
{
isMouseDown = true;
x = e.X;
y = e.Y;
g = this.selectorForm.CreateGraphics();
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (!isMouseDown) return;
this.selectorForm.Invalidate();
g.FillRectangle(brush, this.getRectangle(x, y, e.X, e.Y));
g.DrawRectangle(pen, this.getRectangle(x, y, e.X, e.Y));
}
这是我的selectorForm
internal class SelectorForm : Form
{
protected override void OnPaintBackground(PaintEventArgs e)
{
}
}
An example when I draw a rectangle (several overlapping rectangles)
并且Invalidate()
无效,因为我覆盖OnPaintBackground
。但是,如果我不执行此操作,请执行this.selectorForm.Show()
,my screen becomes gray。
那么如何在屏幕上绘制一个不透明度为0.1的矩形?
谢谢!
答案 0 :(得分:1)
这是一个适合我的例子。
关键部分是:
Paint
事件和其 Graphics
Clear(BackgroundColor)
,否则我会看到相同的工件您可能希望适应您设置事件的方式,我只是这样做以加快测试速度。
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
DoubleBuffered = true;
Opacity = 0.1f;
// a color that will allow using the mouse on the form:
BackColor = Color.GreenYellow;
TransparencyKey = BackColor;
}
Point mDown = Point.Empty;
Point mCur = Point.Empty;
private void Form2_MouseDown(object sender, MouseEventArgs e)
{
mDown = e.Location;
}
private void Form2_MouseUp(object sender, MouseEventArgs e)
{
mDown = Point.Empty;
}
private void Form2_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return;
mCur = e.Location;
Invalidate();
}
private void Form2_Paint(object sender, PaintEventArgs e)
{
if (mDown == Point.Empty) return;
Size s = new System.Drawing.Size(Math.Abs(mDown.X - mCur.X),
Math.Abs(mDown.Y - mCur.Y) );
Point topLeft = new Point(Math.Min(mDown.X, mCur.X),
Math.Min(mDown.Y, mCur.Y));
Rectangle r = new Rectangle(topLeft, s);
e.Graphics.Clear(this.BackColor); // <--- necessary!
e.Graphics.FillRectangle(Brushes.Bisque, r ); // <--- pick your..
e.Graphics.DrawRectangle(Pens.Red, r); // <--- colors!
}
}
}
答案 1 :(得分:0)
您可以尝试以下代码:
g.Clear();
g.FillRectangle(brush, this.getRectangle(x, y, e.X, e.Y));
g.DrawRectangle(pen, this.getRectangle(x, y, e.X, e.Y));