【问题标题】:C# graphics draw transparent rectangle over areaC# 图形在区域上绘制透明矩形
【发布时间】:2011-09-09 13:30:45
【问题描述】:

我有两个相互叠加的图像,并且希望能够清除顶部图像的一部分。通常,如果我想清除图像的一部分,我只需将其绘制为背景颜色即可

g.FillRectangle(Brushes.White,x,y,width,height);

但如果我在顶部图像上执行此操作,则底部图像的区域会被白色矩形覆盖。我试过做

g.FillRectangle(Brushes.Transparent,x,y,width,height);

但这似乎并没有清除所有以前内容的区域。有什么办法可以使该区域中的像素透明?

【问题讨论】:

    标签: c# graphics


    【解决方案1】:
    //using System.Drawing.Drawing2D;
    
    g.FillRectangle(Brushes.White,x,y,width,height);
    g.CompositingMode = CompositingMode.SourceCopy;    
    g.FillRectangle(Brushes.Transparent,x,y,width,height);
    

    【讨论】:

    • 这个不行,CompositingMode.SourceCopy只影响RGB通道。
    • 正是我想要的
    【解决方案2】:

    这是不可能的。

    GDI+ 和Graphics 类不支持分层绘图;一旦你覆盖了之前的图像,这些像素就消失了

    您应该通过调用需要两个矩形的DrawImage 重载来重新绘制您想要显示的上一张图像的部分。

    如果下部图像包含透明部分,您应该首先通过调用FillRectangle 将该区域清除为白色(或任何您的原始背景),以便正确覆盖透明度。

    【讨论】:

      【解决方案3】:

      另一种选择是不直接绘制图像。使用:

      System.Windows.Forms.PictureBox
      

      它的属性

      Region
      

      更改图像的可见性/透明度。区域不必是矩形。它可以从任何一组行中定义。

      PS:Brushes.Transparent 并不是真正的透明,而是父容器的BackColor。

      【讨论】:

      • 您的PS 仅在控件上绘制时为真。位图支持完整的 alpha 混合透明度。但是,Transparent 表示“什么也不做”;这并不意味着“擦除像素”。
      【解决方案4】:
      float[][] ptsArray ={
                  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, 0.5f, 0},
                  new float[] {0, 0, 0, 0, 1}};
                  ColorMatrix clrMatrix = new ColorMatrix(ptsArray);
                  ImageAttributes imgAttributes = new ImageAttributes();
                  imgAttributes.SetColorMatrix(clrMatrix,
                  ColorMatrixFlag.Default,
                  ColorAdjustType.Bitmap);
                  _ImageThumb.Height, imgAttributes);
                  e.Graphics.DrawImage(_ImageThumb,new Rectangle(0, 0, _ImageThumb.Width,_ImageThumb.Height),0, 0, _ImageThumb.Width, _ImageThumb.Height,GraphicsUnit.Pixel, imgAttributes);
      

      //使用set clip & region进行绘制

      【讨论】:

        猜你喜欢
        • 2011-07-11
        • 2016-03-12
        • 1970-01-01
        • 2016-05-25
        • 1970-01-01
        • 1970-01-01
        • 2016-10-05
        • 1970-01-01
        • 2012-04-15
        相关资源
        最近更新 更多