我有一个不透明度设置为0的表单。我怎样才能在该表单中绘制一个填充的矩形,即50%透明?
//brush1 transparency is set at 128 (50%)
SolidBrush brush1 = new SolidBrush(Color.FromArgb(128, 100, 100, 100));
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Grapics.FillRectangle(brush1, rectangle1);
}
如果我使用e.Graphics
进行绘画,则屏幕上不会绘制任何内容,因为表单的不透明度为0.
我尝试使用Graphics g = Graphics.FromHwnd(IntPtr.Zero);
进行绘制,但速度很慢(只有透明度较慢的刷子),这绝对是无效的。
编辑:我这样做是为了绘制到屏幕上。表单正在使用透明画布以实现这一目标。我尝试使用BackColor = Color.LightGreen; TransparencyKey = Color.LightGreen;
,但只绘制了矩形LightGreen
。
这就是我想要实现的目标:
答案 0 :(得分:1)
您可以使用两种形式来实现此目的。一个在背景上具有部分不透明度,另一个在前景上具有透明度键。
透明窗口位于名为Foreground_Form的表单上的Label中。 背景是一个名为Form_TransparentBack
的表单<强> Form_TransparentBack 强>
public partial class Form_TransparentBack : Form
{
public Form_TransparentBack(Form _foregroundForm)
{
InitializeComponent();
StartPosition = _foregroundForm.StartPosition;
Location = _foregroundForm.Location;
Size = _foregroundForm.Size;
_foregroundForm.Resize += _foregroundForm_Resize;
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
_foregroundForm.LocationChanged += _foregroundForm_LocationChanged;
ShowInTaskbar = false;
BackColor = Color.WhiteSmoke;
Opacity = 0.5;
Timer timer = new Timer() { Interval = 10};
timer.Tick += delegate(object sn, EventArgs ea)
{
(sn as Timer).Stop();
_foregroundForm.ShowDialog();
};
timer.Start();
Show();
}
void _foregroundForm_LocationChanged(object sender, EventArgs e)
{
Location = (sender as Form).Location;
}
void _foregroundForm_Resize(object sender, EventArgs e)
{
WindowState = (sender as Form).WindowState;
Size = (sender as Form).Size;
}
}
<强> Foreground_Form 强>
public partial class Foreground_Form : Form
{
public Foreground_Form()
{
InitializeComponent();
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; // required
TransparencyKey = this.BackColor; // required
StartPosition = FormStartPosition.CenterScreen;
this.Paint += Foreground_Form_Paint;
}
void Foreground_Form_Paint(object sender, PaintEventArgs e)
{
//this is for the Stroke
e.Graphics.DrawRectangle(Pens.White, new Rectangle(0, 0, Width - 1, Height - 1));
}
}
现在您可以使用透明背景调用任何表单。对于透明度,您应将TransparencyKey设置为要显示的表单。
private void button1_Click(object sender, EventArgs e)
{
new Form_TransparentBack(new Foreground_Form());
}