2016-03-24 194 views
1

我有一個PictureBox控件的背景顏色設置爲透明。我想在這個控件上繪製圖像(來源:https://en.wikipedia.org/wiki/Seven-segment_display#/media/File:7-segment.svg),但不是透明背景,而是背景顏色是白色(不幸的是,繪圖不支持alpha通道)。繪製透明圖像不起作用

以下是我嘗試繪製位圖:

private void DrawPictureBox() 
{ 
    pbScreen.Image = Update(); 
} 

private Bitmap CreateBackgroundBitmap() 
{ 
    Bitmap bitmap = (Bitmap)Properties.Resources.ResourceManager.GetObject("empty"); 
    bitmap.MakeTransparent(Color.White); 

    return bitmap; 
} 

private ImageAttributes GetImageAttributes() 
{ 
    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, Contrast, 0}, 
     new float[] {0, 0, 0, 0, 1}}; 

    ColorMatrix colorMatrix = new ColorMatrix(matrixItems); 

    ImageAttributes imageAtt = new ImageAttributes(); 
    imageAtt.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); 

    return imageAtt; 
} 

private void DrawSegment(ref Graphics g, Digit digit, int Position = 0) 
{ 
    if (digit == null) 
     return; 

    Bitmap buffer = digit.CreateBitmapFromFile(digit.CreateFileNameFromContent()); 
    buffer.MakeTransparent(Color.White); 

    g.DrawImage(buffer, new Rectangle(0 + Position * 43, 0, 43, 67), 0.0f, 0.0f, 43, 67, GraphicsUnit.Pixel, this.GetImageAttributes()); 

} 

public Bitmap Update() 
{ 
    Bitmap buffer = CreateBackgroundBitmap(); 

    Graphics g = Graphics.FromImage(buffer); 

    g.DrawImage(buffer, new Rectangle(0, 0, 301, 67), 0.0f, 0.0f, 301, 67, GraphicsUnit.Pixel, this.GetImageAttributes()); 

    if (State == Powerstate.on) 
    { 
     // Draw segments 
     for (int i = 0; i < digits.Count(); i++) 
     { 
      DrawSegment(ref g, digits[i], i); 

      if (digits[i]?.Dot == Dot.dot_on) 
      { 
       DrawPoint(ref g, digits[i], i); 
      } 
     } 
    } 

    return buffer; 
} 

繪製線段(畫點是相似的)按預期工作,但繪製背景就不會接受那些被與否有關「GetImageAttributes創建透明度( )」。

另一個奇怪的事情是,如果我添加

g.Clear(color: Color.Black); 

g.DrawImage(buffer, new Rectangle(0, 0, 301, 67), 0.0f, 0.0f, 301, 67, GraphicsUnit.Pixel, this.GetImageAttributes()); 
在Update()方法我Grapics 'G'

簡直就是黑 - 不管我是否保留或刪除

bitmap.MakeTransparent(Color.White); 

'CreateBackgroundBitmap()',但在黑色背景上繪製段作爲exp ected?

有人看到問題在哪裏嗎?我錯過了什麼?

非常感謝:)

回答

0

好吧,我明白了。我想我不明白Graphics對象是如何與位圖進行交互的,即圖形對象是由什麼構成的。

下面是它的,就必須改變:

public Bitmap Update() 
{ 
    Bitmap background = new Bitmap(301, 67); 
    Graphics g = Graphics.FromImage(background); 

    g.Clear(color: Color.White); 

    Bitmap buffer = CreateBackgroundBitmap(); 

    g.DrawImage(buffer, new Rectangle(0, 0, 301, 67), 0.0f, 0.0f, 301, 67, GraphicsUnit.Pixel, this.GetImageAttributes()); 

    if (State == Powerstate.on) 
    { 
     for (int i = 0; i < digits.Count(); i++) 
     { 
      DrawSegment(ref g, digits[i], i); 

      if (digits[i]?.Dot == Dot.dot_on) 
      { 
       DrawPoint(ref g, digits[i], i); 
      } 
     } 
    } 

    return background; 
}