不建议使用PictureBox 对于winform的机制无法这么简单的实现透明
默说最容易的实现方法还是GDI自绘
一个可以测试的代码如下 我定义了一个自定义控件来完成这个工作
其实关键代码不是很多-w-
void Main()
{
Form f = new Form();
f.Size = new Size(600,500);
Button btn1 = new Button();
btn1.Text = "打开图片1";
btn1.Location = new Point(0,0);
f.Controls.Add(btn1);
Button btn2 = new Button();
btn2.Text = "打开图片2";
btn2.Location = new Point(0,30);
f.Controls.Add(btn2);
TrackBar bar1 = new TrackBar();
bar1.Location = new Point(0,60);
bar1.Maximum = 100;
bar1.Value = 100;
f.Controls.Add(bar1);
MyPicBox picBox = new MyPicBox();
picBox.Location = new Point(100,0);
picBox.Size = new Size(600,600);
picBox.Image2Location = new Point(100,100);
f.Controls.Add(picBox);
btn1.Click += (o,e) => {
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK) {
picBox.Image1 = Image.FromFile(dlg.FileName);
picBox.Invalidate();
}
};
btn2.Click += (o,e) => {
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK){
picBox.Image2 = Image.FromFile(dlg.FileName);
picBox.Invalidate();
}
};
bar1.ValueChanged += (o,e) => {
picBox.Image2Opacity = bar1.Value * 0.01f;
picBox.Invalidate();
};
Application.Run(f);
}
// Define other methods and classes here
public class MyPicBox : UserControl {
public MyPicBox() {
this.Image2Opacity = 1f;
base.DoubleBuffered = true;
}
public Image Image1 {get;set;}
public Image Image2 {get;set;}
public Point Image2Location {get;set;}
public float Image2Opacity {get;set;}
protected override void OnPaint(PaintEventArgs e) {
if (Image1 != null)
e.Graphics.DrawImage(Image1,
new Rectangle(Point.Empty, Image1.Size),
new Rectangle(Point.Empty, Image1.Size),
GraphicsUnit.Pixel);
if (Image2 != null) {
ImageAttributes attr = new ImageAttributes();
attr.SetColorMatrix(new ColorMatrix(){ Matrix33 = Image2Opacity });
e.Graphics.DrawImage(Image2,
new Rectangle(Image2Location.X, Image2Location.Y, Image2.Width, Image2.Height),
0,0, Image2.Width, Image2.Height,
GraphicsUnit.Pixel,
attr);
}
}
}
效果图
控件有个属性
Opacity=0是完全隐藏
Opacity=1是完全显示
你可以根据自己需要设置成0.5 0.3这样的浮点数就行
那你将Form中的TranspraencyKey设置为你要变透明的颜色 比如你提到的 蓝色
但这有个缺点 就是颜色一定要纯... 不然得话... 你可以试试
希望能解决您的问题。
1、控件.backgroundcolor透明
2、上层控件.parent=下层控件。