简体   繁体   English

C#:根据系统颜色创建更亮/更暗的颜色

[英]C#: Create a lighter/darker color based on a system color

Duplicate 重复

How do I adjust the brightness of a color? 如何调整颜色的亮度?
How do I determine darker or lighter color variant of a given color? 如何确定给定颜色的深色或浅色变体?
Programmatically Lighten a Color 以编程方式减轻颜色


Say I have 说我有

var c = Color.Red;

Now I want to create a new Color that is lighter or darker than that color. 现在我想创建一个比该颜色更亮或更暗的新Color How can I do that without too much hassle? 没有太多麻烦我怎么能这样做?

ControlPaint .Light .Dark .DarkDark等

Color lightRed = ControlPaint.Light( Color.Red );

I recently blogged about this . 我最近在博客上写了这个 The main idea is to apply a given correction factor to each of the color components. 主要思想是将给定的校正因子应用于每个颜色分量。 The following static method modifies the brightness of a given color with a specified correction factor and produces a darker or a lighter variant of that color: 以下静态方法使用指定的校正因子修改给定颜色的亮度,并生成该颜色的较暗或较浅的变体:

/// <summary>
/// Creates color with corrected brightness.
/// </summary>
/// <param name="color">Color to correct.</param>
/// <param name="correctionFactor">The brightness correction factor. Must be between -1 and 1. 
/// Negative values produce darker colors.</param>
/// <returns>
/// Corrected <see cref="Color"/> structure.
/// </returns>
public static Color ChangeColorBrightness(Color color, float correctionFactor)
{
    float red = (float)color.R;
    float green = (float)color.G;
    float blue = (float)color.B;

    if (correctionFactor < 0)
    {
        correctionFactor = 1 + correctionFactor;
        red *= correctionFactor;
        green *= correctionFactor;
        blue *= correctionFactor;
    }
    else
    {
        red = (255 - red) * correctionFactor + red;
        green = (255 - green) * correctionFactor + green;
        blue = (255 - blue) * correctionFactor + blue;
    }

    return Color.FromArgb(color.A, (int)red, (int)green, (int)blue);
}

You can also do this using a Lerp function. 您也可以使用Lerp功能执行此操作。 There's one in XNA, but it's easy to write yourself. XNA中有一个,但你自己写的很容易。

See my answer to this similar question for a C# implementation. 请参阅对C#实现的类似问题的回答

The function lets you do this: 该功能可以让你这样做:

// make red 50% lighter:
Color.Red.Lerp( Color.White, 0.5 );

// make red 75% darker:
Color.Red.Lerp( Color.Black, 0.75 );

// make white 10% bluer:
Color.White.Lerp( Color.Blue, 0.1 );

Most of these 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 HSLColor class 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;
}

Taking the core method of @Pavel's answer I prepared the following two little extension methods for a more intuitive (at least for me) signature. 采用@ Pavel答案的核心方法,我准备了以下两个小扩展方法,以便更直观(至少对我来说)签名。

public static Color LightenBy(this Color color, int percent)
{
    return ChangeColorBrightness(color, percent/100.0);
}

public static Color DarkenBy(this Color color, int percent)
{
    return ChangeColorBrightness(color, -1 * percent / 100.0); 
}

Here's some javascript code I use for lightening/darkening a given colour. 这是我使用的一些javascript代码,用于使给定颜色变亮/变暗。 You could use it as a base for an equivalent C# function 您可以将它用作等效C#函数的基础

It works by calculating a distance from pure white of each of the RGB components and then adjusts this distance by the provided factor. 它的工作原理是计算每个RGB分量的纯白色距离,然后用提供的因子调整该距离。 The new distance is used to calculate the new colour. 新距离用于计算新颜色。 A factor of between 0 and 1 darkens, a factor higher than 1 lightens 0到1之间的因子变暗,高于1的因子变亮

function Darken( hexColor, factor )
    {   
        if ( factor < 0 ) factor = 0;

        var c = hexColor;
        if ( c.substr(0,1) == "#" )
        {
            c = c.substring(1);
        }

        if ( c.length == 3 || c.length == 6 )
        {
            var i = c.length / 3;

            var f;  // the relative distance from white

            var r = parseInt( c.substr(0, i ), 16 );
            f = ( factor * r / (256-r) );
            r = Math.floor((256 * f) / (f+1));

            r = r.toString(16);
            if ( r.length == 1 ) r = "0" + r;

            var g = parseInt( c.substr(i, i), 16);
            f = ( factor * g / (256-g) );
            g = Math.floor((256 * f) / (f+1));
            g = g.toString(16);
            if ( g.length == 1 ) g = "0" + g;

            var b = parseInt( c.substr( 2*i, i),16 );
            f = ( factor * b / (256-b) );
            b = Math.floor((256 * f) / (f+1));
            b = b.toString(16);
            if ( b.length == 1 ) b = "0" + b;

            c =  r+g+b;
         }   

         return "#" + c;

    }

You can also simply work on the RGB percentage to get it lighter or darker as you want, Here is an example for how to make a color darker x% than it is: 您也可以根据需要简单地处理RGB百分比以使其更亮或更暗。下面是一个如何使颜色比x更暗的示例:

//_correctionfactory in percentage, e.g 50 = make it darker 50%
    private Color DarkerColor(Color color, float correctionfactory = 50f)
    {
        const float hundredpercent = 100f;                        
        return Color.FromArgb((int)(((float)color.R / hundredpercent) * correctionfactory),
            (int)(((float)color.G / hundredpercent) * correctionfactory), (int)(((float)color.B / hundredpercent) * correctionfactory));
    }

One more thing we can also reverse the process to be lighter instead, Only we getting the result of 255 - RGB and then multiply it by the percentage we want like the following example: 还有一件事我们也可以将过程反转为更轻,只有我们得到255的结果 - RGB然后乘以我们想要的百分比,如下例所示:

private Color LighterColor(Color color, float correctionfactory = 50f)
    {
        correctionfactory = correctionfactory / 100f;
        const float rgb255 = 255f;
        return Color.FromArgb((int)((float)color.R + ((rgb255 - (float)color.R) * correctionfactory)), (int)((float)color.G + ((rgb255 - (float)color.G) * correctionfactory)), (int)((float)color.B + ((rgb255 - (float)color.B) * correctionfactory))
            );
    }

Hope that helps. 希望有所帮助。

I changed Pavel Vladov function to modify even RGB component, to get shades on any combination of R/G/B directions: 我改变了Pavel Vladov函数来修改甚至RGB分量,以获得R / G / B方向的任何组合的阴影:

Public Function ChangeColorShades(color As Color, correctionFactor As Single, bR As Boolean, bG As Boolean, bB As Boolean) As Color


    Dim red As Single = CSng(color.R)
    Dim green As Single = CSng(color.G)
    Dim blue As Single = CSng(color.B)

    If (correctionFactor < 0) Then

        correctionFactor = 1 + correctionFactor
        If bR Then
            red *= correctionFactor
        End If
        If bG Then
            green *= correctionFactor
        End If
        If bB Then
            blue *= correctionFactor
        End If


    Else
        If bR Then
            red = (255 - red) * correctionFactor + red
        End If
        If bG Then
            green = (255 - green) * correctionFactor + green
        End If
        If bB Then
            blue = (255 - blue) * correctionFactor + blue
        End If

    End If

    Return color.FromArgb(color.A, CInt(red), CInt(green), CInt(blue))
End Function

I made a site that does this colorglower.com You can check it out to see a demo. 我做了一个这个colorglower.com的网站你可以看看它看演示。

Here's the javascript code i used. 这是我使用的javascript代码。

function lighten(color) {

// convert to decimal and change luminosity
var luminosity = 0.01
var computedColors = new Array();
var newColor = "#",
    c, i, n, black = 0,
    white = 255;
for (n = 0; n < 10; n++) {
    for (i = 0; i < 3; i++) {
        c = parseInt(color.substr(i * 2, 2), 16);
        c = Math.round(Math.min(Math.max(black, c + (luminosity * white)), white)).toString(16);
        newColor += ("00" + c).substr(c.length);
    }

    computedColors[n] = newColor;
    var arrayUnique = checkIfArrayIsUnique(computedColors);
    if (arrayUnique == false) {
        computedColors.pop();
        break;
    }

    computedColors[n] = newColor;
    newColor = "#";
    luminosity += calcPercentage();
}

return computedColors;

} }

What this code does is it receives a hex color and then it outputs 10 lightest color versions of it and puts in in the array. 这段代码的作用是接收十六进制颜色,然后输出10个最亮的颜色版本并放入数组中。 You can change the luminosity to whatever you like to adjust the shade percentage. 您可以将亮度更改为您喜欢的任何值,以调整阴影百分比。 To darken the colors you just need to change: 要使颜色变暗,您需要更改:

luminosity -= calcPercentage();

Using HSI converter library(search google). 使用HSI转换库(搜索谷歌)。 And then, adjust I channel for lighter/darker color. 然后,调整I通道以获得更亮/更暗的颜色。

Take a look at the ControlPaint class: 看一下ControlPaint类:

MSDN: Members of ControlPaint MSDN:ControlPaint的成员

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM