今天写一篇关于RGB转Hex 和 Hex 转 RGB的文章,首先可以先点下面这篇进行基础补充
typescript代码
class Dou {
public hex:string[] = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
// constructor(){}
getHexStr(n:number):string{
return this.hex[n]
}
getNum(s:string):number{
if(/^\d$/.test(s)){
return parseInt(s)
}
else{
let x = [
['A','10'],
['B','11'],
['C','12'],
['D','13'],
['E','14'],
['F','15']
]
for(let i=0;i
if(s.toLocaleUpperCase() == x[i][0]){
return parseInt(x[i][1])
}
}
}
return 0;
}
/**
*
* @param rgb 'rgb(222,22,222)'
* @returns '#ffffff'
*/
rgbTohex(rgb:string):string{
//rgb = 'rgb(244,244,80)' 这种格式
let arrTotail:string[];
//获得 [244,244,80] 这数格式
arrTotail = rgb.slice(
rgb.indexOf('(')+1,
rgb.indexOf(')')
).split(',')
//把数组里的内容转为16进制
arrTotail = arrTotail.map((e):string=>{
let self = this;
let e1:number = Number(e)
let result:number = e1 / 16;
let first:string = this.getHexStr((result | 0))
let second:string = (function(result):string{
let index = result.indexOf('.')
return index == -1
? self.getHexStr(0)
: self.getHexStr(
(16 * parseFloat(result.slice(index)))
)
}(result.toString()))
return first+second;
})
return '#' + arrTotail.join('');
}
/**
*
* @param hex '#ffffff || #fff'
* @returns 'rgb(222,22,222)'
*/
hexTorgb(hex:string):string{
//hex = '#fff' || '#ffffff'
let self = this;
//a 把fff这类简写转为非简写ffffff
let a = hex.length == 4
? (
(hex.slice(1).split('').map((e):string=>{
return e+e;
})).join('')
)
: hex.slice(1)
//把ffffff 转为 ff,ff,ff
let b = '';
for(var i=0;i
if(i > 0 && i < a.length - 1 && i % 2 == 1){
b+=(a[i]+',')
}
else{
b+=a[i]
}
}
//把ff,ff,ff 转为数组 [ff,ff,ff] 并使用map转换为[255,255,255]
let c = b.split(',')
c = c.map((e)=>{
let a = e[0]
let b = e[1]
return (self.getNum(a) * 16 + self.getNum(b)).toString()
})
return `rgb(${c[0]},${c[1]},${c[2]})`
}
}
export default Dou
mac 上加代码块无效?没法了先这样吧