프로그래밍 방식으로 색상 밝게
자극
임의의 색상을 사용하여 몇 가지 음영을 밝게하는 방법을 찾고 싶습니다. 그래야 프로그래밍 방식으로 한 색상에서 더 밝은 버전으로 멋진 그라디언트를 만들 수 있습니다. 그라디언트는 UI에서 배경으로 사용됩니다.
가능성 1
분명히 RGB 값을 분할하여 특정 양만큼 개별적으로 늘릴 수 있습니다. 이것이 실제로 내가 원하는 것입니까?
가능성 2
두 번째 생각은 RGB를 HSV / HSB / HSL (Hue, Saturation, Value / Brightness / Lightness)로 변환하고 밝기를 약간 높이고 채도를 약간 낮추고 다시 RGB로 변환하는 것이 었습니다. 일반적으로 원하는 효과가 있습니까?
두 번째 옵션을 선택하겠습니다. 일반적으로 RGB 공간은 색상 조작 (한 색상에서 다른 색상으로의 전환 생성, 색상을 밝게 / 어둡게하는 등)을 수행하는 데 실제로 좋지 않습니다. 다음은 HSL에서 RGB로 /에서 /로 변환하는 빠른 검색으로 찾은 두 사이트입니다.
- "컴퓨터 그래픽의 기초"에서
- C #의 일부 소스 코드 -다른 프로그래밍 언어에 쉽게 적용 할 수 있어야합니다.
으로 웨지는 말했다 , 당신은 곱셈 밝은 일을하게하고 싶지만, 색상 중 하나가 포화 될 때까지 그에만 작동합니다 (즉, 255 이상에 도달). 이 시점에서 값을 255로 고정 할 수 있지만 밝아 질수록 색조가 미묘하게 변경됩니다. 색조를 유지하려면 (가장 낮음) / (가장 낮음) 비율을 유지하려고합니다.
다음은 Python의 두 가지 함수입니다. 첫 번째는 RGB 값이 넘어 가면 255로 고정하는 순진한 접근 방식을 구현합니다. 두 번째는 초과 값을 재분배하여 색조를 그대로 유지합니다.
def clamp_rgb(r, g, b):
return min(255, int(r)), min(255, int(g)), min(255, int(b))
def redistribute_rgb(r, g, b):
threshold = 255.999
m = max(r, g, b)
if m <= threshold:
return int(r), int(g), int(b)
total = r + g + b
if total >= 3 * threshold:
return int(threshold), int(threshold), int(threshold)
x = (3 * threshold - total) / (3 * m - total)
gray = threshold - x * m
return int(gray + x * r), int(gray + x * g), int(gray + x * b)
RGB 값 (224,128,0)으로 시작하여 1.0, 1.1, 1.2 등을 2.0까지 곱하여 그라디언트를 만들었습니다. 위쪽 절반은를 사용한 결과 clamp_rgb
이고 아래쪽 절반 은를 사용한 결과입니다 redistribute_rgb
. 오버플로를 재배포하면 RGB 색상 공간을 벗어나지 않고도 훨씬 더 나은 결과를 얻을 수 있다는 것을 쉽게 알 수 있습니다.
비교를 위해 여기에 Python colorsys
모듈에 의해 구현 된 HLS 및 HSV 색상 공간의 동일한 그라디언트가 있습니다. L
구성 요소 만 수정되었으며 결과 RGB 값에 대해 클램핑이 수행되었습니다. 결과는 비슷하지만 모든 픽셀에 대해 색상 공간 변환이 필요합니다.
C #에서 :
public static Color Lighten(Color inColor, double inAmount)
{
return Color.FromArgb(
inColor.A,
(int) Math.Min(255, inColor.R + 255 * inAmount),
(int) Math.Min(255, inColor.G + 255 * inAmount),
(int) Math.Min(255, inColor.B + 255 * inAmount) );
}
나는 이것을 모든 곳에서 사용했습니다.
System.Windows.Forms 네임 스페이스의 ControlPaint 클래스에는 Light 및 Dark의 정적 메서드가 있습니다.
public static Color Dark(Color baseColor, float percOfDarkDark);
이러한 메서드는 HLSColor의 개인 구현을 사용합니다. 이 구조체가 공용이고 System.Drawing에 있었으면합니다.
또는 Color 구조체에서 GetHue, GetSaturation, GetBrightness를 사용하여 HSB 구성 요소를 가져올 수 있습니다. 불행히도 역변환을 찾지 못했습니다.
RGB로 변환하고 원래 색상과 대상 색상 (종종 흰색)을 선형으로 보간합니다. 따라서 두 색상 사이에 16 가지 음영을 원하는 경우 다음을 수행합니다.
for(i = 0; i < 16; i++)
{
colors[i].R = start.R + (i * (end.R - start.R)) / 15;
colors[i].G = start.G + (i * (end.G - start.G)) / 15;
colors[i].B = start.B + (i * (end.B - start.B)) / 15;
}
주어진 색상의 더 밝거나 더 어두운 버전을 얻으려면 밝기를 수정해야합니다. 색상을 HSL 또는 HSB 색상으로 변환하지 않고도 쉽게 수행 할 수 있습니다. 예를 들어 색상을 더 밝게 만들려면 다음 코드를 사용할 수 있습니다.
float correctionFactor = 0.5f;
float red = (255 - color.R) * correctionFactor + color.R;
float green = (255 - color.G) * correctionFactor + color.G;
float blue = (255 - color.B) * correctionFactor + color.B;
Color lighterColor = Color.FromArgb(color.A, (int)red, (int)green, (int)blue);
자세한 내용이 필요하면 내 블로그에서 전체 기사를 읽어보십시오 .
이전에 유용한 답변과 함께 매우 유사한 질문이 제기되었습니다 . 주어진 색상의 더 어둡거나 밝은 색상 변형을 어떻게 결정합니까?
짧은 대답 : "충분히 좋은"것이 필요한 경우 RGB 값에 상수를 곱하고 정확도가 필요한 경우 HSV로 변환합니다.
나는 Andrew의 대답과 Mark의 대답을 사용하여 이것을 만들었 습니다 (1/2013 현재 ff에 대한 범위 입력 없음).
function calcLightness(l, r, g, b) {
var tmp_r = r;
var tmp_g = g;
var tmp_b = b;
tmp_r = (255 - r) * l + r;
tmp_g = (255 - g) * l + g;
tmp_b = (255 - b) * l + b;
if (tmp_r > 255 || tmp_g > 255 || tmp_b > 255)
return { r: r, g: g, b: b };
else
return { r:parseInt(tmp_r), g:parseInt(tmp_g), b:parseInt(tmp_b) }
}
HS (LVB)로 변환하고 밝기를 높인 다음 다시 RGB로 변환하는 것이 색조 및 채도 값에 영향을주지 않고 안정적으로 색상을 밝게하는 유일한 방법입니다 (즉, 다른 방식으로 변경하지 않고 색상 만 밝게하는 것).
저는이 두 가지 방법을 모두 수행했습니다. Possibility 2를 사용하면 훨씬 더 나은 결과를 얻을 수 있습니다.
가능성 1에 대해 생성 한 모든 간단한 알고리즘은 제한된 범위의 시작 채도에서만 잘 작동합니다.
(1) 사용되는 색상과 밝기를 제한 할 수 있고 (2) 렌더링에서 계산을 많이 수행하는 경우 Poss 1을 살펴보고 싶을 것입니다.
UI의 배경을 생성하는 데에는 많은 음영 계산이 필요하지 않으므로 Poss 2를 제안합니다.
-알.
IF you want to produce a gradient fade-out, I would suggest the following optimization: Rather than doing RGB->HSB->RGB for each individual color you should only calculate the target color. Once you know the target RGB, you can simply calculate the intermediate values in RGB space without having to convert back and forth. Whether you calculate a linear transition of use some sort of curve is up to you.
Method 1: Convert RGB to HSL, adjust HSL, convert back to RGB.
Method 2: Lerp the RGB colour values - http://en.wikipedia.org/wiki/Lerp_(computing)
See my answer to this similar question for a C# implementation of method 2.
Pretend that you alpha blended to white:
oneMinus = 1.0 - amount
r = amount + oneMinus * r
g = amount + oneMinus * g
b = amount + oneMinus * b
where amount
is from 0 to 1, with 0 returning the original color and 1 returning white.
You might want to blend with whatever the background color is if you are lightening to display something disabled:
oneMinus = 1.0 - amount
r = amount * dest_r + oneMinus * r
g = amount * dest_g + oneMinus * g
b = amount * dest_b + oneMinus * b
where (dest_r, dest_g, dest_b)
is the color being blended to and amount
is from 0 to 1, with zero returning (r, g, b)
and 1 returning (dest.r, dest.g, dest.b)
I didn't find this question until after it became a related question to my original question.
However, using insight from these great answers. I pieced together a nice two-liner function for this:
Programmatically Lighten or Darken a hex color (or rgb, and blend colors)
Its a version of method 1. But with over saturation taken into account. Like Keith said in his answer above; use Lerp to seemly solve the same problem Mark mentioned, but without redistribution. The results of shadeColor2
should be much closer to doing it the right way with HSL, but without the overhead.
A bit late to the party, but if you use javascript
or nodejs
, you can use tinycolor library, and manipulate the color the way you want:
tinycolor("red").lighten().desaturate().toHexString() // "#f53d3d"
I would have tried number #1 first, but #2 sounds pretty good. Try doing it yourself and see if you're satisfied with the results, it sounds like it'll take you maybe 10 minutes to whip up a test.
Technically, I don't think either is correct, but I believe you want a variant of option #2. The problem being that taken RGB 990000 and "lightening" it would really just add onto the Red channel (Value, Brightness, Lightness) until you got to FF. After that (solid red), it would be taking down the saturation to go all the way to solid white.
변환은 특히 RGB 및 Lab으로 직접 이동할 수 없기 때문에 성가신 일이지만 색차와 광도 값을 분리하고 원하는 것을 실제로 달성하기 위해 광도를 수정하기를 원한다고 생각합니다.
color-tools ruby 라이브러리 에서 색상 공간을 변환하는 코드를 찾을 수 있습니다.
나는이 블로그 포스트 쇼가 어떻게 델파이에서이 작업을 수행 할 수 있음을. ColorRGBToHSL 및 ColorHLSToRGB 함수가 표준 라이브러리의 일부이기 때문에 매우 간단합니다.
다음은 Python에서 RGB 색상을 밝게하는 예입니다.
def lighten(hex, amount):
""" Lighten an RGB color by an amount (between 0 and 1),
e.g. lighten('#4290e5', .5) = #C1FFFF
"""
hex = hex.replace('#','')
red = min(255, int(hex[0:2], 16) + 255 * amount)
green = min(255, int(hex[2:4], 16) + 255 * amount)
blue = min(255, int(hex[4:6], 16) + 255 * amount)
return "#%X%X%X" % (int(red), int(green), int(blue))
참고 URL : https://stackoverflow.com/questions/141855/programmatically-lighten-a-color
'IT TIP' 카테고리의 다른 글
연속 배열과 비 연속 배열의 차이점은 무엇입니까? (0) | 2020.10.31 |
---|---|
React Native에서 텍스트를 세로 (90도 회전)로 만들려면 어떻게해야합니까? (0) | 2020.10.31 |
자바 스크립트에서 객체가 해시인지 배열인지 어떻게 식별 할 수 있습니까? (0) | 2020.10.31 |
T-SQL의 Levenshtein 거리 (0) | 2020.10.31 |
투영과 선택이란 무엇입니까? (0) | 2020.10.31 |