[英]Drawing transparent image doesn't work
我有一個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()'中,但在黑色背景上繪制片段按預期工作?!
有人看到問題出在哪里嗎? 我錯過了什么?
非常感謝 :)
好吧,我明白了。 我想我不明白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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.