色值转换hex和rgba互换

2022-05-16  本文已影响0人  读书练习生

色值转换,总结了一下。ts+类写法。

export class SiderBarStyleColorUtil{

  componentToHex(c:any) {

    let hex = c.toString(16);

    return hex.length == 1 ? "0" + hex : hex;

  }

//rgb转hex

rgbToHex(r:any, g:any, b:any) {

    return "#" + this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b);

  }

//hex转rgb

hexToRgb(hex:any) {

    let 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;

  }

  // 获取rgba(a,b,c,d)中的某一项

  rgbaNum(rgba:any, index:any) {

    let val = rgba.match(/(\d(\.\d+)?)+/g);

    return val[index];

  }

  // 获取rgba(a,b,c,d)中的全部

  getRgba(params:string) {

    let arr = [this.rgbaNum(params, 0), this. rgbaNum(params, 1), this.rgbaNum(params, 2)];

    return arr;

  }

}

export const siderBarStyleColorUtil = new SiderBarStyleColorUtil();

上一篇下一篇

猜你喜欢

热点阅读