C# 如何调整颜色的亮度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/737217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I adjust the brightness of a color?
提问by Brad
I would like to darken an existing color for use in a gradient brush. Could somebody tell me how to do this please?
我想将现有颜色变暗以用于渐变画笔。有人能告诉我怎么做吗?
C#, .net 2.0, GDI+
C#、.net 2.0、GDI+
采纳答案by Marc Gravell
As a simple approach, you can just factor the RGB values:
作为一种简单的方法,您可以只考虑 RGB 值:
Color c1 = Color.Red;
Color c2 = Color.FromArgb(c1.A,
(int)(c1.R * 0.8), (int)(c1.G * 0.8), (int)(c1.B * 0.8));
(which should darken it; or, for example, * 1.25 to brighten it)
(应该使其变暗;或者,例如,* 1.25 使其变亮)
回答by Richard
Convert from RGB to HSV (or HSL), then adjust the V (or L) down and then convert back.
从 RGB 转换为 HSV(或 HSL),然后向下调整 V(或 L),然后再转换回来。
While System.Drawing.Color
provides methods to get hue (H), saturation (S) and brightness it does not provide much in the way of other conversions, notable nothing to create a new instance from HSV (or HSV values), but the conversion is pretty simple to implement. The wikipedia articles give decent converage, starting here: "HSL and HSV".
虽然System.Drawing.Color
提供了获取色调 (H)、饱和度 (S) 和亮度的方法,但它并没有提供太多其他转换的方式,值得注意的是没有什么可以从 HSV(或 HSV 值)创建新实例,但转换非常简单实施。维基百科文章提供了不错的聚合,从这里开始:“ HSL 和 HSV”。
回答by dommer
Here's some C# code for the conversions Richard mentioned:
以下是 Richard 提到的转换的一些 C# 代码:
回答by Alex
You could also try using
你也可以尝试使用
ControlPaint.Light(baseColor, percOfLightLight)
or
或者
ControlPaint.Dark(baseColor, percOfDarkDark)
回答by TugboatCaptain
While the aforementioned methods do darken the color but they adjust the hue way to much so the result doesn't look very good. The best answer is to use Rich Newman's HSLColorclass and adjust the luminosity.
虽然上述方法确实使颜色变暗,但它们将色调方式调整得太多,因此结果看起来不太好。最好的答案是使用Rich Newman 的 HSLColor类并调整亮度。
public Color Darken(Color color, double darkenAmount) {
HSLColor hslColor = new HSLColor(color);
hslColor.Luminosity *= darkenAmount; // 0 to 1
return hslColor;
}
回答by VB.net Coder
You must keep track that the value does not extend below 0 or above 255
您必须跟踪该值不低于 0 或高于 255
Best approach is to use Math.Max/Math.MIn
最好的方法是使用 Math.Max/Math.MIn
dim newValue as integer = ...
'correct value if it is below 0 or above 255
newValue = Math.Max(Math.Min(newValue,255),0)