c# - 从透明形式的图像中删除轮廓

标签 c# visual-studio-2015

我正在尝试将窗口形式转换为透明形式,并使其仅显示一个对象。但是它在我的对象周围仍然有一条线(描边),它并不像我想要的那样完美。我怎样才能取出线(笔划)? (附上图片对比。)

enter image description here

这是我的代码:

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;
}

最佳答案

您的图像具有半透明像素。 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 像素格式,PNG 通常具有这种格式。

最后请注意,由于图像有很多 黑色,您应该选择不同的颜色。 紫红色 在野外相当罕见,但在龙的世界中可能不是,你想随机选择一些颜色..

此外:您想要设置 pictureBox1.BackColor = Color.Transparent..

最后:有时在函数签名中添加一个threshold 参数来设置一个级别,从该级别打开或关闭 alpha 是有意义的。

这是一个用法示例:

this.BackColor = Color.FromArgb(1,2,3,4);
this.TransparencyKey = this.BackColor;
UnSemi((Bitmap)this.pictureBox1.Image);

enter image description here

关于c# - 从透明形式的图像中删除轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43372549/

相关文章:

c# - 如何在 ASP.Net 中更改 UnauthorizedAccessException 重定向到的位置

c++ - VS2015 的 Boost nuget 包

javascript - Visual Studio - Javascript 智能感知?

html - 什么会导致错误 '(CSS 3.0): ":-webkit-autofill"is not a valid pseudo-class. '

c# - 在 C# 中使用 Using 的不同方式

c# - 基本对象 WebView 如何在 HTML 树中导航?

visual-studio-2015 - 如何在iisexpress vs2015中设置具有相同端口和域但路径不同的多个应用程序

c++ - Visual Studio 错误 D8016 : '/ZI' and '/Gy' command-line options are incompatible

c# - 在展开嵌套的 "Dispose"语句时处理 "using"抛出的异常

c# - Int64 在使用 SimpleJSON 传递到函数时会更改值