我目前正在使用 Winforms 和.NET 3.5(工作环境)开发一种简单的图像编辑工具。
.NET 3.5
我有一个要求,当用户单击选择工具按钮时,将出现一个正方形(C#中的矩形),以便他们可以在100x100和之间进行缩放400x400。我已修复此问题- 问题在于使矩形的背景透明。
100x100
400x400
对于是否支持透明度.NET 3.5,我还不清楚,我尝试了以下方法:
SetStyle(ControlStyles.SupportsTransparentBackColor, true); pnlSelectArea.BackColor = Color.Transparent; pnlSelectArea.ForeColor = Color.Transparent; selectArea1.BackColor = Color.Transparent; selectArea1.ForeColor = Color.Transparent;
但这没有效果-任何建议将不胜感激。
这是我的特殊控件,其中包含一个不透明度属性,它100%有效:
using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.Design; public class TranspCtrl : Control { public bool drag = false; public bool enab = false; private int m_opacity = 100; private int alpha; public TranspCtrl() { SetStyle(ControlStyles.SupportsTransparentBackColor, true); SetStyle(ControlStyles.Opaque, true); this.BackColor = Color.Transparent; } public int Opacity { get { if (m_opacity > 100) { m_opacity = 100; } else if (m_opacity < 1) { m_opacity = 1; } return this.m_opacity; } set { this.m_opacity = value; if (this.Parent != null) { Parent.Invalidate(this.Bounds, true); } } } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle = cp.ExStyle | 0x20; return cp; } } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; Rectangle bounds = new Rectangle(0, 0, this.Width - 1, this.Height - 1); Color frmColor = this.Parent.BackColor; Brush bckColor = default(Brush); alpha = (m_opacity * 255) / 100; if (drag) { Color dragBckColor = default(Color); if (BackColor != Color.Transparent) { int Rb = BackColor.R * alpha / 255 + frmColor.R * (255 - alpha) / 255; int Gb = BackColor.G * alpha / 255 + frmColor.G * (255 - alpha) / 255; int Bb = BackColor.B * alpha / 255 + frmColor.B * (255 - alpha) / 255; dragBckColor = Color.FromArgb(Rb, Gb, Bb); } else { dragBckColor = frmColor; } alpha = 255; bckColor = new SolidBrush(Color.FromArgb(alpha, dragBckColor)); } else { bckColor = new SolidBrush(Color.FromArgb(alpha, this.BackColor)); } if (this.BackColor != Color.Transparent | drag) { g.FillRectangle(bckColor, bounds); } bckColor.Dispose(); g.Dispose(); base.OnPaint(e); } protected override void OnBackColorChanged(EventArgs e) { if (this.Parent != null) { Parent.Invalidate(this.Bounds, true); } base.OnBackColorChanged(e); } protected override void OnParentBackColorChanged(EventArgs e) { this.Invalidate(); base.OnParentBackColorChanged(e); } }