我的可移动面板包含图像控件和图像前面的透明用户控件(PathDraw)。
我在PathDraw
类中使用以下代码使其透明。
public partial class PathDraw : UserControl
{
public PathDraw()
{
...
InitializeComponent();
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
BackColor = Color.Transparent;
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x20;
return cp;
}
}
protected override void OnPaintBackground(System.Windows.Forms.PaintEventArgs pevent)
{
// Do nothing.
}
...
在MouseDown
事件中,绘制一条包含alpha 100的行并添加到pathList
以供将来使用
private void PathDraw_MouseDown(object sender, MouseEventArgs e)
{
...
var gr = this.CreateGraphics();
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
var path = GetPath(pointList[pointList.Count - 1], e.Location);
gr.DrawPath(pathPen, path);
pointList.Add(e.Location);
pathList.Add(path);
}
private GraphicsPath GetPath(Point p1, Point p2)
{
GraphicsPath path = new GraphicsPath();
path.AddLine(p1, p2);
return path;
}
public PathDraw()
{
// create semi transparent pen
Color semiTransparentColor = Color.FromArgb(100, Color.Blue);
pathPen = new Pen(semiTransparentColor, 4);
pathPen.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;
pathPen.StartCap = System.Drawing.Drawing2D.LineCap.Round;
pathPen.EndCap = System.Drawing.Drawing2D.LineCap.Round;
...
}
问题:当移动面板和图像刷新时,重绘路径基于paint事件中的ClipRectangle
。
检查e.ClipRectangle
以及路径是否与ClipRectangle相交,重绘
但是一条线会失去透明度并变得不透明。
private void PathDraw_Paint(object sender, PaintEventArgs e)
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
for (int i = 0; i < pathList.Count; i++)
{
if (e.ClipRectangle.IntersectsWith(Rectangle.Round(pathList[i].GetBounds())))
{
e.Graphics.DrawPath(pathPen, pathList[i]);
}
}
}
我认为我的错误是在不清除的情况下绘制完整的行。
如何在重绘之前清除线条?或任何解决方案。
修改 我出于某种原因使用此控件来显示图像
public partial class CompoundControl : UserControl
{
private System.Windows.Forms.Label backLabel;
public CompoundControl()
{
InitializeComponent();
}
//Image _img;
public Image Image
{
get
{
return backLabel.Image;
}
set
{
backLabel.Image = value;
//_img = value;
}
}
public event PaintEventHandler Painted;
private void backLabel_Paint(object sender, PaintEventArgs e)
{
if (this.Painted != null)
{
this.Painted(this, e);
}
}
...
并在表单类中检查Painted
事件
private void image_Painted(object sender, PaintEventArgs e)
{
var clip = e.ClipRectangle;
clip.Offset((sender as CompoundControl).Location);
pathDrawObj.Invalidate(clip);
}
我更改此控件并正常工作。 CompoundControl
中有什么问题?