IT TIP

두 색상 간의 대 비율을 프로그래밍 방식으로 계산하는 방법은 무엇입니까?

itqueen 2020. 12. 30. 19:58
반응형

두 색상 간의 대 비율을 프로그래밍 방식으로 계산하는 방법은 무엇입니까?


매우 간단합니다. 노란색과 흰색을 사용합니다.

back_color = {r:255,g:255,b:255}; //white
text_color = {r:255,g:255,b:0}; //yellow

하나님의 지구에서 보편적 인 상수의 물리학 법칙은 노란색 텍스트는 흰색 배경에서 읽을 수 없지만 파란색 텍스트는 읽을 수 있다는 사실을 만듭니다.

사용자 정의 가능한 위젯을 위해 변환 기능을 찾은 가능한 모든 색상 모델을 시도했습니다. 숫자 비교만으로 녹색은 흰색이고 노란색은 불가능하다고 말할 수 없습니다.

나는 Adsense (모든 인터넷의 Budda에 의해 생성 된)를보고 그들이 무엇을했는지 추측하고 그들은 프리셋과 컬러 셀 거리 계산을 만들었다. 그렇게 할 수 없습니다. 내 사용자는 텍스트를 읽을 수있는 한 가장 망막에 염증을 일으키고 비 미적인 조합을 선택할 권리가 있습니다.


위키 백과에 따르면 휘도의 그레이 스케일 표현으로 변환 할 때 "적색, 녹색, 청색의 값을 얻어야한다"고 다음 비율로 혼합합니다. R : 30 % G : 59 % B : 11 %

따라서 흰색은 100 % 휘도를, 노란색은 89 %를 갖습니다. 동시에 녹색은 59 %만큼 작습니다. 11 %는 41 % 차이보다 거의 4 배나 낮습니다!

그리고 라임 ( #00ff00) 조차도 많은 양의 텍스트를 읽는 데 좋지 않습니다.

대비 색상이 좋은 IMHO의 밝기는 적어도 50 %는 달라야합니다. 그리고이 밝기는 그레이 스케일로 변환하여 측정해야합니다.

upd : 최근 웹에서 w3 문서의 공식을 사용 하는 포괄적 인 도구발견했습니다. 임계 값은 # 1.4 에서 가져올 수 있습니다. 다음은이 고급 기능에 대한 구현입니다.

function luminanace(r, g, b) {
    var a = [r, g, b].map(function (v) {
        v /= 255;
        return v <= 0.03928
            ? v / 12.92
            : Math.pow( (v + 0.055) / 1.055, 2.4 );
    });
    return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
}
function contrast(rgb1, rgb2) {
    return (luminanace(rgb1[0], rgb1[1], rgb1[2]) + 0.05)
         / (luminanace(rgb2[0], rgb2[1], rgb2[2]) + 0.05);
}
contrast([255, 255, 255], [255, 255, 0]); // 1.074 for yellow
contrast([255, 255, 255], [0, 0, 255]); // 8.592 for blue
// minimal recommended contrast ratio is 4.5, or 3 for larger font-sizes

대비를 계산하는 방법에는 여러 가지가 있지만 일반적인 방법은 다음 공식입니다.

brightness = (299*R + 587*G + 114*B) / 1000

두 가지 색상 모두에 대해이 작업을 수행 한 다음 차이를 가져옵니다. 이것은 분명히 흰색의 노란색보다 흰색의 파란색에 훨씬 더 큰 대비를 제공합니다.


키릴 로이드 답변을 기반으로 :

16 진수 값을 전달하여 대비 및 발광을 계산하는 Angular 서비스 :

.service('ColorContrast', [function() {
var self = this;

/**
 * Return iluminance value (base for getting the contrast)
 */
self.calculateIlluminance = function(hexColor) {
    return calculateIluminance(hexColor);
};

/**
 * Calculate contrast value to white
 */
self.contrastToWhite = function(hexColor){
    var whiteIlluminance = 1;
    var illuminance = calculateIlluminance(hexColor);
    return whiteIlluminance / illuminance;
};

/**
* Bool if there is enough contrast to white
*/
self.isContrastOkToWhite = function(hexColor){
    return self.contrastToWhite(hexColor) > 4.5;
};

/**
 * Convert HEX color to RGB
 */
var hex2Rgb = function(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
};

/**
 * Calculate iluminance
 */
var calculateIlluminance = function(hexColor) {
    var rgbColor = hex2Rgb(hexColor);
    var r = rgbColor.r, g = rgbColor.g, b = rgbColor.b;
    var a = [r, g, b].map(function(v) {
        v /= 255;
        return (v <= 0.03928) ?
            v / 12.92 :
            Math.pow(((v + 0.055) / 1.055), 2.4);
    });
    return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
};

}]);

최근에이 페이지에서 답을 찾았고 코드를 사용하여 Adobe Illustrator 용 스크립트를 만들어 명암비를 계산했습니다.

여기에서 결과를 볼 수 있습니다. http://screencast.com/t/utT481Ut

저에게 혼란스럽고 Adobe 확장 스크립트에서 작동하지 않는 위 스크립트의 약식 표기법 중 일부입니다. 따라서 kirilloid가 공유 한 코드의 개선 / 해석을 공유하면 좋을 것이라고 생각했습니다.

function luminance(r, g, b) {
    var colorArray = [r, g, b];
    var colorFactor;
    var i;
    for (i = 0; i < colorArray.length; i++) {
        colorFactor = colorArray[i] / 255;
        if (colorFactor <= 0.03928) {
            colorFactor = colorFactor / 12.92;
        } else {
            colorFactor = Math.pow(((colorFactor + 0.055) / 1.055), 2.4);
        }
        colorArray[i] = colorFactor;
    }
    return (colorArray[0] * 0.2126 + colorArray[1] * 0.7152 + colorArray[2] * 0.0722) + 0.05;
}

물론이 함수를 호출해야합니다.

for 루프 내에서 일러스트 레이터 객체에서 모든 색상을 얻습니다.

//just a snippet here to demonstrate the notation
var selection = app.activeDocument.selection;
for (i = 0; i < selection.length; i++) {
   red[i] = selection[i].fillColor.red;
   //I left out the rest,because it would become to long
}

//this can then be used to calculate the contrast ratio.
var foreGround = luminance(red[0], green[0], blue[0]);
var background = luminance(red[1], green[1], blue[1]);
luminanceValue = foreGround / background;
luminanceValue = round(luminanceValue, 2);

//for rounding the numbers I use this function:
function round(number, decimals) {
   return +(Math.round(number + "e+" + decimals) + "e-" + decimals);
}

명암비에 대한 추가 정보 : http://webaim.org/resources/contrastchecker/


module.exports = function colorcontrast (hex) {
    var color = {};

    color.contrast = function(rgb) {
        // check if we are receiving an element or element background-color
        if (rgb instanceof jQuery) {
            // get element background-color
            rgb = rgb.css('background-color');
        } else if (typeof rgb !== 'string') {
            return;
        }

        // Strip everything except the integers eg. "rgb(" and ")" and " "
        rgb = rgb.split(/\(([^)]+)\)/)[1].replace(/ /g, '');

        // map RGB values to variables
        var r = parseInt(rgb.split(',')[0], 10),
            g = parseInt(rgb.split(',')[1], 10),
            b = parseInt(rgb.split(',')[2], 10),
            a;

        // if RGBA, map alpha to variable (not currently in use)
        if (rgb.split(',')[3] !== null) {
            a = parseInt(rgb.split(',')[3], 10);
        }

        // calculate contrast of color (standard grayscale algorithmic formula)
        var contrast = (Math.round(r * 299) + Math.round(g * 587) + Math.round(b * 114)) / 1000;

        return (contrast >= 128) ? 'black' : 'white';
    };

    // Return public interface
    return color;

};

참조 URL : https://stackoverflow.com/questions/9733288/how-to-programmatically-calculate-the-contrast-ratio-between-two-colors

반응형