【发布时间】:2010-10-18 17:50:15
【问题描述】:
我想将现有颜色变暗以用于渐变画笔。有人可以告诉我该怎么做吗?
C#、.net 2.0、GDI+
【问题讨论】:
我想将现有颜色变暗以用于渐变画笔。有人可以告诉我该怎么做吗?
C#、.net 2.0、GDI+
【问题讨论】:
作为一种简单的方法,您可以只考虑 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));
(应该使它变暗;或者,例如,* 1.25 使其变亮)
【讨论】:
int R = (rgb.R * amt > 255) ? 255 : (int)(rgb.R * amt); int G = (rgb.G * amt > 255) ? 255 : (int)(rgb.G * amt); int B = (rgb.B * amt > 255) ? 255 : (int)(rgb.B * amt); Color c2 = Color.FromArgb(1, R, G, B);
Math.Clamp(rgb.R * amt, 0, 255), Math.Clamp(rgb.G * amt, 0, 255), Math.Clamp(rgb.B * amt, 0, 255) 等会更容易更高效(它只执行一次操作)
你也可以试试
ControlPaint.Light(baseColor, percOfLightLight)
或
ControlPaint.Dark(baseColor, percOfDarkDark)
【讨论】:
从 RGB 转换为 HSV(或 HSL),然后向下调整 V(或 L),然后再转换回来。
虽然System.Drawing.Color 提供了获取色调 (H)、饱和度 (S) 和亮度的方法,但它并没有提供太多的其他转换方式,值得注意的是从 HSV(或 HSV 值)创建新实例,但是转换很容易实现。维基百科文章提供了不错的融合,从这里开始:“HSL and HSV”。
【讨论】:
下面是 Richard 提到的转换的一些 C# 代码:
【讨论】:
h /= 6.0;之前添加if (h >= 6f) h -= 6f; if (h < 0f) h += 6f;到RGB2HSL函数。
虽然上述方法确实会使颜色变暗,但它们会调整色调方式,因此结果看起来不太好。最好的答案是使用Rich Newman's HSLColor 类并调整亮度。
public Color Darken(Color color, double darkenAmount) {
HSLColor hslColor = new HSLColor(color);
hslColor.Luminosity *= darkenAmount; // 0 to 1
return hslColor;
}
【讨论】:
hslColor.Luminosity *= 1.2; Luminosity 是一个从 0 到 240 的值。如果超过 240,它会自动限制在 240。
您必须跟踪该值不低于 0 或高于 255
最好的方法是使用 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)
【讨论】: