【问题标题】:Picturebox slider control transparencyPicturebox滑块控制透明度
【发布时间】:2017-11-28 17:05:40
【问题描述】:

我的表单中有一个 PictureBox,并在其中加载了一张图片。

我需要这个PictureBox来改变透明度(不透明度,visibilit..等),因为我需要用户更好地看到这个PictureBox后面的图像,所以当他想要的时候,他只需拖动控制滑块,图像就开始了一步一步地变成隐形,直到他发现它没问题,比如说 50% 的透明度。

我添加了控制滑块,但无法找到完成其余部分的方法。我尝试了pictureBox.Opacity,pictureBox.Transparency,没有任何效果。

【问题讨论】:

  • 您的目标是什么:Winforms、WPF、ASP..? 总是正确标记您的问题! - 在 Winforms 中没有简单的方法可以做到这一点。您将不得不修改 PBox.Image 的 alpha。请参阅ColorMatrix for a fast way.. WPF 可以轻松做到,我相信。
  • 本来就没有“后面”的概念 - 无论位置如何,所有控件都是同级的。请阅读How to Ask 并采取tour
  • 本来就没有'behind'的概念至少在Winforms中有嵌套,并且图片框嵌套到表单或标签页或组框或面板或一些容器。所以,有一个背后的概念。

标签: c# transparency picturebox opacity


【解决方案1】:

在 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;

【讨论】:

  • 非常感谢你,我的朋友。我已经尝试了很多天。我是 C# 新手。这很完美。正是我需要的方式。非常感谢你。
猜你喜欢
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多