tags:

views:

54

answers:

2

I have a Color, and I have a method that should return a more "transparent" version of that color. I tried the following method:

public static Color SetTransparency(int A, Color color)
{
   return Color.FromArgb(A, color.R, color.G, color.B);
}

but for some reason, no matter what the A is, the returned Color's transparency level just won't change.

Any idea?

+2  A: 

Well, it looks okay to me, except that you're using Color.R (etc) instead of color.R - are you sure you're actually using the returned Color rather than assuming it will change the existing color? How are you determining that the "transparency level" won't change?

Here's an example showing that the alpha value is genuinely correct in the returned color:

using System;
using System.Drawing;

class Test
{
    static Color SetTransparency(int A, Color color)
    {
        return Color.FromArgb(A, color.R, color.G, color.B);
    }

    static void Main()
    {
        Color halfTransparent = SetTransparency(127, Color.Black);
        Console.WriteLine(halfTransparent.A); // Prints 127
    }
}

No surprises there. It would be really helpful if you'd provide a short but complete program which demonstrates the exact problem you're having. Are you sure that whatever you're doing with the color even supports transparency?

Note that this method effectively already exists as Color.FromArgb(int, Color).

Jon Skeet
Yes, I'm using the returned `Color`.
Ngu Soon Hui
@Jon, I think maybe the component I use has an issue. I'll ask the component provider and see
Ngu Soon Hui
A: 

There might be a problem with your naming. I made a standard Windows Forms project, with 2 buttons and added some code, when clicking the buttons their respective colors do actually fade away.

And I agree with Jon Skeet, you are implementing a duplicate method, also all parameter names should begin with a lower case letter, so 'a' instead of 'A'

code:

private void Form1_Load(object sender, EventArgs e)
{
    button1.BackColor = Color.Red;
    button2.BackColor = Color.Green;
}

private void button1_Click(object sender, EventArgs e)
{
    Color c = button1.BackColor;
    button1.BackColor = Color.FromArgb(Math.Max(c.A - 10, (byte)0), c.R, c.G, c.B);
}

private void button2_Click(object sender, EventArgs e)
{
    Color c = button2.BackColor;
    button2.BackColor = Color.FromArgb(Math.Max(c.A - 10, (byte)0), c.R, c.G, c.B);
}

public static Color SetTransparency(int a, Color color)
{
    return Color.FromArgb(a, color.R, color.G, color.B);
}
MrFox