在 winforms 中,您必须修改 PictureBox.Image 的 alpha。
要快速做到这一点,请使用ColorMatrix!
这是一个例子:
轨迹条码:
Image original = null;
private void trackBar1_Scroll(object sender, EventArgs e)
{
if (original == null) original = (Bitmap) pictureBox1.Image.Clone();
pictureBox1.BackColor = Color.Transparent;
pictureBox1.Image = SetAlpha((Bitmap)original, trackBar1.Value);
}
要使用ColorMatrix,我们需要这个 using 子句:
using System.Drawing.Imaging;
现在是SetAlpha 函数;请注意,它基本上是MS link..的克隆:
static Bitmap SetAlpha(Bitmap bmpIn, int alpha)
{
Bitmap bmpOut = new Bitmap(bmpIn.Width, bmpIn.Height);
float a = alpha / 255f;
Rectangle r = new Rectangle(0, 0, bmpIn.Width, bmpIn.Height);
float[][] matrixItems = {
new float[] {1, 0, 0, 0, 0},
new float[] {0, 1, 0, 0, 0},
new float[] {0, 0, 1, 0, 0},
new float[] {0, 0, 0, a, 0},
new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(matrixItems);
ImageAttributes imageAtt = new ImageAttributes();
imageAtt.SetColorMatrix( colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
using (Graphics g = Graphics.FromImage(bmpOut))
g.DrawImage(bmpIn, r, r.X, r.Y, r.Width, r.Height, GraphicsUnit.Pixel, imageAtt);
return bmpOut;
}
注意ColorMatrix 期望它的元素是比例因子,1 是标识。 TrackBar.Value 来自0-255,就像Bitmap alpha 频道..
另请注意,该函数会创建一个新 Bitmap,这可能会导致GDI 泄漏。看来,PictureBox 负责处理它;至少用任务管理器测试它('Details' - 打开 GDI-objects 列!)显示没有问题:-)
最后说明:这当且仅当PictureBox 嵌套在它“后面”的控件中才有效!如果它只是重叠这是行不通的!!在我的示例中,它位于TabPage 上,即Container 上,你放在它上面的任何东西都会嵌套在里面。如果我把它放到Panel 上,它会起作用。但是PictureBoxes 不是容器。因此,如果您希望另一个PictureBox 出现在其后面,那么您需要代码 来创建嵌套:pboxTop.Parent = pBoxBackground; pboxTop.Location = Point.Empty;