我试图将窗体转换为透明,并使其只显示一个对象。但它仍然在我的物体周围有一条线(笔划),它并不像我想的那样完美。我该如何取出线条(笔划)? (附图片进行比较。)
这是我的代码:
private void Form1_Load(object sender, EventArgs e)
{
this.FormBorderStyle = FormBorderStyle.None;
this.Width = this.pictureBox1.Width;
this.Height = this.pictureBox1.Height;
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.BackColor = Color.Black;
this.TransparencyKey = this.pictureBox1.BackColor;
}
答案 0 :(得分:2)
您的图片有半透明像素。 TransparencyKey
只会使一个颜色透明。因此,临界像素将显示图像颜色和Parent
控件或表单颜色的混合。
这是一个通过使所有半透明像素完全透明来消除所有半透明像素的功能:
using System.Runtime.InteropServices;
..
public static void UnSemi(Bitmap bmp)
{
Size s = bmp.Size;
PixelFormat fmt = bmp.PixelFormat;
Rectangle rect = new Rectangle(Point.Empty, s);
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, fmt);
int size1 = bmpData.Stride * bmpData.Height;
byte[] data = new byte[size1];
System.Runtime.InteropServices.Marshal.Copy(bmpData.Scan0, data, 0, size1);
for (int y = 0; y < s.Height; y++)
{
for (int x = 0; x < s.Width; x++)
{
int index = y * bmpData.Stride + x * 4;
// alpha, threshold = 255
data[index + 3] = (data[index + 3] < 255) ? (byte)0 : (byte)255;
}
}
System.Runtime.InteropServices.Marshal.Copy(data, 0, bmpData.Scan0, data.Length);
bmp.UnlockBits(bmpData);
}
请注意,这也意味着漂亮的抗锯齿外观会变得有些粗糙......
另请注意,例程假设采用32位ARGB像素格式,PNGs
通常会有。
最后请注意,由于图片的很多 Black
,您应该选择不同的颜色。 Fuchsia
在野外是相当罕见的,但也许不是在龙的世界中,你想要选择一些随机的颜色..
另外:您想设置pictureBox1.BackColor = Color.Transparent
..
最后:有时候在函数签名中添加一个threshold
参数来设置一个开启或关闭alpha的级别是有意义的。
以下是一个用法示例:
this.BackColor = Color.FromArgb(1,2,3,4);
this.TransparencyKey = this.BackColor;
UnSemi((Bitmap)this.pictureBox1.Image);
答案 1 :(得分:0)
使用具有透明背景的Png图像
设置您的控件/表格背景颜色和透明键到图像中不存在的颜色