外观
UColor - 颜色处理工具类
约 850 字大约 3 分钟
2025-11-06
UColor 是一个强大的颜色处理工具类,支持多种颜色格式之间的转换和操作。
功能特性
- 支持多种颜色格式:HEX、RGB、RGBA、HSL、HSLA、颜色关键字
- 颜色格式之间的相互转换
- 透明度设置和获取
- 颜色验证和解析
快速开始
1. 导入 UColor 类
import { UColor } from '@/uni_modules/uview-unix'2. 创建颜色实例
// 从十六进制创建
const color1 = new UColor('#ff0000')
// 从RGB创建
const color2 = new UColor('rgb(255, 0, 0)')
// 从RGBA创建
const color3 = new UColor('rgba(255, 0, 0, 0.5)')
// 从HSL创建
const color4 = new UColor('hsl(0, 100%, 50%)')
// 从颜色关键字创建
const color5 = new UColor('red')API 参考
构造函数
new UColor(input?: string)实例方法
颜色转换
| 方法 | 描述 | 返回值 |
|---|---|---|
toRgbString() | 转换为RGB/RGBA字符串 | string |
toHslString() | 转换为HSL/HSLA字符串 | string |
toHex(a?: boolean) | 转换为十六进制字符串(不带#) | string |
toHexString(a?: boolean) | 转换为带#的十六进制字符串 | string |
颜色获取
| 方法 | 描述 | 返回值 |
|---|---|---|
toRgb() | 获取RGBA颜色数组 | number[] |
toHsl() | 获取HSLA颜色数组 | number[] |
toHsv() | 获取HSVA颜色数组 | number[] |
getAlpha() | 获取透明度值 | number |
getFormat() | 获取颜色格式 | string |
颜色设置
| 方法 | 描述 | 参数 |
|---|---|---|
fromString(color: string) | 从字符串解析颜色 | color: 颜色字符串 |
fromRgb(r: number, g: number, b: number, a: number) | 从RGB值设置颜色 | r, g, b: 0-255; a: 0-1 |
fromHsl(h: number, s: number, l: number) | 从HSL值设置颜色 | h: 0-360; s, l: 0-1 |
fromHsv(h: number, s: number, v: number) | 从HSV值设置颜色 | h: 0-360; s, v: 0-100 |
fromHex(hex: string) | 从十六进制字符串设置颜色 | hex: 十六进制字符串 |
setAlpha(alpha: number) | 设置透明度 | alpha: 0-1 |
方法示例
颜色转换
const color = new UColor('#ff0000')
// 转换为RGB字符串
console.log(color.toRgbString()) // 'rgb(255, 0, 0)'
// 转换为RGBA字符串
color.setAlpha(0.5)
console.log(color.toRgbString()) // 'rgba(255, 0, 0, 0.50)'
// 转换为HSL字符串
console.log(color.toHslString()) // 'hsl(0, 100%, 50%, 0.50)'
// 转换为十六进制字符串
console.log(color.toHexString()) // '#ff000080'
// 转换为十六进制(不带#)
console.log(color.toHex()) // 'ff000080'颜色获取
const color = new UColor('#ff0000')
// 获取RGBA数组
console.log(color.toRgb()) // [255, 0, 0, 1]
// 获取HSLA数组
console.log(color.toHsl()) // [0, 100, 50, 1]
// 获取HSVA数组
console.log(color.toHsv()) // [0, 100, 100]
// 获取透明度
console.log(color.getAlpha()) // 1
// 获取颜色格式
console.log(color.getFormat()) // 'HEX'颜色设置
const color = new UColor()
// 从RGB设置
color.fromRgb(255, 0, 0, 1)
// 从HSL设置
color.fromHsl(0, 1, 0.5)
// 从HSV设置
color.fromHsv(0, 100, 100)
// 从十六进制设置
color.fromHex('#00ff00')
// 设置透明度
color.setAlpha(0.5)
// 从字符串设置
color.fromString('blue')支持的颜色格式
1. 十六进制格式
// 3位缩写
new UColor('#f00')
// 6位标准
new UColor('#ff0000')
// 带透明度
new UColor('#ff000080')
// 不带#前缀
new UColor('ff0000')2. RGB/RGBA格式
// 整数格式
new UColor('rgb(255, 0, 0)')
new UColor('rgba(255, 0, 0, 0.5)')
// 百分比格式
new UColor('rgb(100%, 0%, 0%)')
new UColor('rgba(100%, 0%, 0%, 0.5)')3. HSL/HSLA格式
new UColor('hsl(0, 100%, 50%)')
new UColor('hsla(0, 100%, 50%, 0.5)')4. 颜色关键字
new UColor('red')
new UColor('blue')
new UColor('transparent')注意事项
- 颜色值范围:RGB值范围为0-255,HSL的色相范围为0-360,饱和度和亮度范围为0-100%
- 透明度范围:0-1,0表示完全透明,1表示完全不透明
