透明控制的透明控制?

时间:2011-10-24 10:16:33

标签: c# .net winforms transparency picturebox

我创建了一个TransparentTableLayoutPanel:

class TransTablePanel : TableLayoutPanel
{
    public TransTablePanel()
    {

    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams createParams = base.CreateParams;
            createParams.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
            return createParams;
        }
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
        // Do not paint background.
    }
}

一个透明的PictureBox(我尝试使用 BackColor =透明并且它不起作用)

class TransPicBox : PictureBox
{
    public TransPicBox()
    {

    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams createParams = base.CreateParams;
            createParams.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
            return createParams;
        }
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
        // Do not paint background.
    }
}

结果如下:

enter image description here

第一个单元格是带有此绘制事件的PictureBox:

private void picBoxCompass_Paint(object sender, PaintEventArgs e)
    {
        Bitmap b = Properties.Resources.Compass_Rose;
        float rot = PitControl.GetPitbullRotation();
        e.Graphics.DrawImage(rotateImage(b, rot), 0, 0, picBoxCompass.Width, picBoxCompass.Height);
        e.Graphics.DrawLine(LinePen, picBoxCompass.Width / 2, 0, picBoxCompass.Width / 2, picBoxCompass.Height / 2);
        e.Graphics.FillPie(Brushes.Green, picBoxCompass.Width / 2 - 10, picBoxCompass.Height / 2 - 10, 20, 20, 0, 360);
    }

你可以看到它不是透明(黑色背景),第二个细胞是透明的(你可以看到我的表格的背景图片)。

如何让PictureBox透明?

1 个答案:

答案 0 :(得分:2)

好的,我添加了适合我的代码。它不是很好(我想听听它可以做得更好),但也许它会帮助你

public class TransPicBox : Control
{
    public Image Image
    {
        get;
        set;
    }

    public TransPicBox()
    {
        SetStyle(ControlStyles.AllPaintingInWmPaint |
                 ControlStyles.SupportsTransparentBackColor, true);
        base.BackColor = Color.FromArgb(0, 0, 0, 0);//Added this because image wasnt redrawn when resizing form
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {

    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (Image != null)
        {
            e.Graphics.DrawImage(Image, 0, 0, Image.Width, Image.Height);
        }
    }

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x20;
            return cp;
        }
    }
}

您需要设置Image属性。

编辑:注意:图片应采用透明背景(使用* .png格式测试)

结果:

enter image description here