外观
hexToRgba 颜色转换
约 224 字小于 1 分钟
2024-01-01
介绍
将十六进制颜色值(hex)转换为RGB或RGBA颜色字符串。
hexToRgba(hex: string, alpha?: number): string
- 参数
- hex: 十六进制颜色值,支持 #333、#333333 等格式
- alpha: 透明度,0-1 之间的值,默认为 1
- 返回值
<String>RGBA颜色字符串,格式为rgba(r, g, b, a),如果输入无效则返回空字符串
示例代码
<template>
<view>
<text>颜色转换示例</text>
<view>
<text>原始颜色:</text>
<view :style="{ width: '200rpx', height: '100rpx', backgroundColor: '#007AFF', marginBottom: '20rpx' }"></view>
<text>转换为带透明度的颜色:</text>
<view :style="{ width: '200rpx', height: '100rpx', backgroundColor: rgbaColor, marginBottom: '20rpx' }"></view>
</view>
</view>
</template>
<script setup lang="uts">
import { computed } from 'vue'
import { hexToRgba } from '@/uni_modules/uview-unix'
// 转换十六进制颜色为rgba格式
const rgbaColor = computed(() => {
// 将#007AFF转换为50%透明度的rgba格式
return hexToRgba('#007AFF', 0.5)
})
console.log('转换结果:', rgbaColor.value) // 输出: rgba(0, 122, 255, 0.5)
</script>