Extension method or subclass to create a System.Drawing.Color based on another color and an alpha?

StackOverflow https://stackoverflow.com/questions/15820241

質問

I want to create colors in C# (not XAML) using one of the following idioms:

Color transparentblue = TransparentColor(Brushes.Blue, 0.5); // 0.5 => 128
Color transparentblue = Brushes.Blue.SetAlpha(0.5);  // again, 0.5 => 128

I want to get rid of the Color.FromArgb() syntax, which is not designer friendly at all. I also got it working with a static method inside a static class, but the writing got a bit heavy:

public static class ColorGenerators {        
    public static Color GetTransparentColor (Color color, double opacity) {
        byte op = (byte)(opacity*255);

        return Color.FromArgb(op, color.R, color.G, color.B);
    }
}

// To be used as
var transparentblue = ColorGenerators.GetTransparentColor(Color.Blue, 0.5);

I still would prefer the Extension Method approach, and it seems to me that soon our company would benefit from methods similar to the ones described in this question, so I wonder what they would look like (given that Color is a struct, not a class).

役に立ちましたか?

解決

How about something like this:

public static class ColorExtensions
{        
    public static Color WithAlpha(this Color color, double opacity) 
    {
        byte op = (byte)(opacity*255);
        return Color.FromArgb(op, color.R, color.G, color.B);
    }
}

The key is the this keyword in the first parameter. That (as well as being a static method in a static class) indicates to the compiler that this is an extension method.

Color transparentblue = Color.Blue.WithAlpha(0.5);

Further Reading

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top