색상코드 Hex, RGBA 관계와 변환 코드
2025. 3. 28. 15:45
728x90
반응형

Hex

  • 16진수(hexadecimal) 형식으로 색상을 표현하는 방법으로 # 기호로 시작하고, 뒤에 6자리의 16진수 숫자가 오는 #RRGGBB 형식을 사용합니다.
  • 이 6자리 숫자는 세 부분으로 나눠지며, 각 부분은 2자리씩 할당되어 각 부분은 빨강(R), 초록(G), 파랑(B) 색상의 비율을 나타냅니다.

  • Hex 색상 코드는 기본적으로 6자리 여야 하며, 3자리로 축약하는 경우도 있습니다.
  • Hex 색상 코드는 투명도를 적용하기 위해 기존 6자리 색상 코드에 투명도(Alpha 값)를 추가하여 RGBA 색상 모델을 사용할 수 있습니다. 이 때는 #RRGGBBAA 형식으로 나타내며, AA는 Alpha 값(투명도)을 나타냅니다.

 

Hex 관련 코드 (Typescript)

// Hex 형식인지 체크
function checkValidHex(hex: string): boolean {
    const hexCode = hex.slice(1);
    const hexRegex = /^([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/;
    return hex.startsWith('#') && hexRegex.test(hexCode);
  }

// Hex's full name 으로 변경
function convertFullHex(hex: string): string {
	if(!checkValidHex(hex)) throw new Error('유효하지 않은 HEX 색상 코드입니다.');
    let hexCode = hex.slice(1);
    switch (hexCode.length) {
      case 3:
        hexCode =
          hexCode
            .split('')
            .map(char => char + char)
            .join('') + 'ff';
        break;
      case 4:
        hexCode = hexCode
          .split('')
          .map(char => char + char)
          .join('');
        break;
      case 6:
        hexCode += 'ff';
        break;
    }
    return `#${hexCode.toLowerCase()}`;
  }

// Hex's short name 으로 변경
function convertShortHex(hex: string): string {
  	if(!checkValidHex(hex)) throw new Error('유효하지 않은 HEX 색상 코드입니다.');
    let hexCode = hex.slice(1);
    if (hexCode.length === 8) {
      const r = hexCode.slice(0, 2);
      const g = hexCode.slice(2, 4);
      const b = hexCode.slice(4, 6);
      const a = hexCode.slice(6, 8);
      if (r[0] === r[1] && g[0] === g[1] && b[0] === b[1] && a[0] === a[1]) hexCode = `${r[0]}${g[0]}${b[0]}${a[0]}`;
      else if (hexCode.slice(-2).toLowerCase() === 'ff') hexCode = hexCode.slice(0, 6);
    }

    switch (hexCode.length) {
      case 4:
        const charA = hexCode.charAt(3);
        if (charA.toLowerCase() === 'f') hexCode = hexCode.slice(0, 3);

        break;
      case 6:
        const r = hexCode.slice(0, 2);
        const g = hexCode.slice(2, 4);
        const b = hexCode.slice(4, 6);
        if (r[0] === r[1] && g[0] === g[1] && b[0] === b[1]) hexCode = `${r[0]}${g[0]}${b[0]}`;
        break;
    }

    return `#${hexCode.toLowerCase()}`;
  }

// Hex 색상코드를 RGBA 색상코드로 변환
function hexToRgba(hex: string): string {
	if(!checkValidHex(hex)) throw new Error('유효하지 않은 HEX 색상 코드입니다.');
    let hexCode = hex.convertFullHex().slice(1);

    const r = parseInt(hexCode.slice(0, 2), 16);
    const g = parseInt(hexCode.slice(2, 4), 16);
    const b = parseInt(hexCode.slice(4, 6), 16);
    const alpha = parseInt(hexCode.slice(6, 8), 16) / 255;

    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

RBGA

  • 색을 Red (빨강), Green (초록), Blue (파랑) 세 가지 기본 색을 혼합하여 다양한 색을 만드는 모델입니다.
  • RGB (Red, Green, Blue) + 색상의 투명도 Alpha 모델으로 rgba(255, 0, 0, 1) 같이 표기
  • 빨강(R), 초록(G), 파랑(B) : 이 값들은 각각 0에서 255까지의 범위를 가집니다. 
    • 각 색상(R, G, B)이 8비트로 표현되며, 2^8 = 256 (0 ~ 255) 개의 색상의 강도를 조절할 수 있습니다.
    • 8비트는 색상 표현에서 효율적이고 충분한 범위를 제공하며 총 16,777,216가지 색상을 만들 수 있게 됩니다.
  • Alpha 투명도 : 0과 1 사이의 투명도를 나타냅니다.
    • 0 : 완전 투명
    • 1 : 완전 불투명

RGBA 관련 코드 (Typescript)

// RGBA 정규식 패턴
const rgbaRegex = /^rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*(\d+(?:\.\d+)?))?\)$/;

// RGBA 형식인지 체크
function checkValidRgba(rgba: string): boolean {
    if (!rgbaRegex.test(rgba)) return false;
    
    const match = rgba.match(rgbaRegex);
    const r = parseInt(match[1]);
    const g = parseInt(match[2]);
    const b = parseInt(match[3]);
    const a = match[4] ? parseFloat(match[4]) : 1;
    
    return !(r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255 || a < 0 || a > 1);
  }
  
// RGBA 색상 코드를 Hex 색상코드로 변환
function rgbaToHex(rgba: string): string {
	if(!checkValidRgba(rgba)) throw new Error('유효하지 않은 RGBA 색상코드 입니다.')
    
 	const match = rgba.match(rgbaRegex);
    const r = parseInt(match[1]).toString(16).padStart(2, '0');
    const g = parseInt(match[2]).toString(16).padStart(2, '0');
    const b = parseInt(match[3]).toString(16).padStart(2, '0');
    const a = match[4] ? Math.round(parseFloat(match[4]) * 255).toString(16).padStart(2, '0')
        : 'ff';
        
    return `#${r}${g}${b}${a}`;
}
728x90
반응형

'기타' 카테고리의 다른 글

색상코드 HSL, HSV, HWB 관계  (0) 2025.04.04