在50%透明度的窗体上绘制透明实心矩形的C#代码

3
我一直在试图模仿Windows 7截图工具,以其半透明灰色层覆盖屏幕的方式,在所选区域内完全透明。 我已经接近成功了。我显示了一个无边框的50%不透明度灰色表单,该表单覆盖整个屏幕,并具有Fuchsia的透明关键字。 然后在该表单的顶部绘制两个矩形。 一个实心的Fuchsia矩形用于透明度,另一个矩形用于红色边框。它可以正常工作,但只有在我执行以下三种操作之一时才行,而这些都不是选项。
  1. 禁用双缓冲使表单在绘制时闪烁
  2. 将桌面色彩模式从32位更改为16位
  3. 使表格100%不透明
以下是我的代码。 有什么建议可以让它正常工作吗?
public partial class frmBackground : Form
{
    Rectangle rect;

    public frmBackground()
    {
        InitializeComponent();

        this.MouseDown += new MouseEventHandler(frmBackground_MouseDown);
        this.MouseMove += new MouseEventHandler(frmBackground_MouseMove);
        this.Paint += new PaintEventHandler(frmBackground_Paint);
        this.DoubleBuffered = true;
        this.Cursor = Cursors.Cross;
    }

    private void frmBackground_MouseDown(object sender, MouseEventArgs e)
    {
        Bitmap backBuffer = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);
        rect = new Rectangle(e.X, e.Y, 0, 0);
        this.Invalidate();
    }

    private void frmBackground_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
            rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top);

        this.Invalidate();
    }

    private void frmBackground_Paint(object sender, PaintEventArgs e)
    {
        Pen pen = new Pen(Color.Red, 3);
        e.Graphics.DrawRectangle(pen, rect);

        SolidBrush brush = new SolidBrush(Color.Fuchsia);
        e.Graphics.FillRectangle(brush, rect);
    }
}
1个回答

0

你可以使用

Brush brush = new SolidBrush(Color.FromArgb(alpha, red, green, blue))

alpha 的取值范围为 0 到 255,因此 alpha 值为 128 时,不透明度为 50%。

这个解决方案可以在 这个问题 中找到。


不,不会的。如果他的表单具有0.2的不透明度,并且画刷具有128个阿尔法值,那么他在矩形上得到的将是0.2 * 128个阿尔法值。 - dimitris93

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接