//////////////////////////// 颜色转化工具
extension hex on String{
Color get color { // 将
return ColorHex.fromHexString(this)
}
}
/////////////////////////////////////////////////////////////
import 'dart:ui'
class ColorTool {
///直接使用 0xffffff
static Color colorHex({required int hex,double? alpha}) {
int r = (hex & 0xFF0000) >> 16
int g = (hex & 0xFF00) >> 8
int b = (hex & 0xFF)
return Color.fromRGBO(r, g, b, alpha??1)
}
///用于通过服务器返回颜色
static colorWithHexString({required String str,double? alpha}) {
if (str.isEmpty) return ColorTool.clear
String cString = str.toUpperCase()
if (cString.length < 6) return ColorTool.clear
var m = cString.startsWith("0X")
var n = cString.startsWith("#")
if (m) {
cString = cString.substring(2)
} else if (n) {
cString = cString.substring(1)
}
if (cString.length != 6) return ColorTool.clear
var start = 0
var end = 2
String r = cString.substring(start, end)
start = start + 2
end = start + 2
String g = cString.substring(start, end)
start = start + 2
end = start + 2
String b = cString.substring(start, end)
return Color.fromRGBO(_hexToInt(r), _hexToInt(g), _hexToInt(b) , alpha??1)
}
static Color clear = Color.fromRGBO(0, 0, 0, 0)
static int _hexToInt(String hex) {
int val = 0
int len = hex.length
for (int i = 0
int hexDigit = hex.codeUnitAt(i)
if (hexDigit >= 48 && hexDigit <= 57) {
val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)))
} else if (hexDigit >= 65 && hexDigit <= 70) {
// A..F
val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)))
} else if (hexDigit >= 97 && hexDigit <= 102) {
// a..f
val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)))
} else {
throw new FormatException("Invalid hexadecimal value")
}
}
return val
}
}
extension ColorHex on Color {
static Color fromHex(int hex,{double? alpha}){ //使用拓展
return ColorTool.colorHex(hex: hex,alpha: alpha)
}
static Color fromHexString(String? hexStr,{double? alpha}){
if(hexStr == null){
return ColorTool.clear
}
return ColorTool.colorWithHexString(str: hexStr,alpha: alpha)
}
}