获得表单图像背景的问题

时间:2010-03-17 19:18:11

标签: c# image winforms

我正在创建一个透明的datagridview

//我得到了父背景图片

位图parentBackGround =新位图(this.Parent.BackgroundImage);

//将我想要创建的区域设置为等于网格的大小

Rectangle rect = new Rectangle(this.Location.X,this.Location.Y,this.Width,this.Height);

//在整个网格中绘制用网格覆盖的背景图像区域,形成“透明”效果。

graphics.DrawImage(parentBackGround.Clone(rect,PixelFormat.Format32bppRgb),gridBounds);

当网格父项的背景图像以正常布局显示时,一切正常,但如果布局是拉伸,居中或任何其他,透明效果消失了,您有什么想法修复它吗?

2 个答案:

答案 0 :(得分:0)

为什么不尝试使用TransparencyKey属性(Form)? http://msdn.microsoft.com/en-us/library/system.windows.forms.form.transparencykey.aspx

答案 1 :(得分:0)

我创建一个位图并将其格式化为网格格式父级的背景图像,然后仅使用它覆盖网格的部分。

我从网格继承并覆盖这些方法:

    protected override void PaintBackground(Graphics graphics, Rectangle clipBounds, Rectangle gridBounds)
    {
        base.PaintBackground(graphics, clipBounds, gridBounds);
        if (DesignMode) return;

        Control tmpParent = Parent;
        int locationX = this.Location.X;
        int locationY = this.Location.Y;
        while (tmpParent.BackgroundImage == null)
        {
            locationX += tmpParent.Location.X;
            locationY += tmpParent.Location.Y;
            tmpParent = tmpParent.Parent;
        }

        Rectangle rectSource = new Rectangle(locationX, locationY, this.Width, this.Height);
        Rectangle rectDest = new Rectangle(0, 0, rectSource.Width, rectSource.Height);

        Bitmap b = new Bitmap(tmpParent.ClientRectangle.Width, tmpParent.ClientRectangle.Height);

        Graphics.FromImage(b).DrawImage(tmpParent.BackgroundImage, tmpParent.ClientRectangle);

        graphics.DrawImage(b, rectDest, rectSource, GraphicsUnit.Pixel);

        SetCellsTransparent();
    }


    public void SetCellsTransparent()
    {
        this.EnableHeadersVisualStyles = false;
        this.ColumnHeadersDefaultCellStyle.BackColor = Color.Transparent;
        this.RowHeadersDefaultCellStyle.BackColor = Color.Transparent;


        foreach (DataGridViewColumn col in this.Columns)
        {
            col.DefaultCellStyle.BackColor = Color.Transparent;
            col.DefaultCellStyle.SelectionBackColor = Color.Transparent;
        }
    }