Wesley
Wesley

Reputation: 51

Remove outline from image on transparent form

I'm trying to transfer window form into transparent, and make it show just an object. But it still has a line (stroke) around my object, it's not really perfect as I wanted. How can I take out the line (stroke)? (Attached a picture to compare.)

enter image description here

Here is my code:

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

Upvotes: 3

Views: 2078

Answers (2)

TaW
TaW

Reputation: 54453

Your image has semi-transparent pixels. TransparencyKey will only make one color transparent. So the borderline pixels will show a mix of the image color and the color of the Parent control or form..

Here is a function that eliminates all semi-transparent pixels by making them fully transparent:

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

Note that this also means that the nice anti-aliased look will get somewhat rough instead..

Also note that the routine assumes a 32 bit ARGB pixel-format, as PNGs will usually have.

Finally note that since the image has a lot of Black you should pick a different color. Fuchsia is rather rare in the wild, but maybe not in the world of dragons and you want to pick some random color..

Also: You want to set the pictureBox1.BackColor = Color.Transparent..

Finally: Sometimes it makes sense to add a threshold parameter to the function signature to set a level from which to turn alpha all on or off..

Here is a usage example:

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

enter image description here

Upvotes: 3

Hasan Elsherbiny
Hasan Elsherbiny

Reputation: 628

Use Png Image Which Has transparent background
set Your Control/Form Background color and transparent Key To Color That Doesn't Exist In the Image

Upvotes: 0

Related Questions