package vision import ( "fmt" "image/color" "strconv" "strings" "apigo.cc/go/rand" ) // ParseColor 将多种格式的十六进制颜色字符串转换为 color.Color // 支持格式: #RRGGBB, #RRGGBBAA, #RGB, #RGBA func ParseColor(hex string) color.Color { hex = strings.ToUpper(strings.TrimPrefix(hex, "#")) // 验证合法字符 for _, ch := range hex { if !((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F')) { return color.RGBA{} } } switch len(hex) { case 3: hex = fmt.Sprintf("%c%c%c%c%c%c", hex[0], hex[0], hex[1], hex[1], hex[2], hex[2]) case 4: hex = fmt.Sprintf("%c%c%c%c%c%c%c%c", hex[0], hex[0], hex[1], hex[1], hex[2], hex[2], hex[3], hex[3]) } switch len(hex) { case 6: // #RRGGBB return color.RGBA{R: parseHex(hex[0:2]), G: parseHex(hex[2:4]), B: parseHex(hex[4:6]), A: 255} case 8: // #RRGGBBAA return color.RGBA{R: parseHex(hex[0:2]), G: parseHex(hex[2:4]), B: parseHex(hex[4:6]), A: parseHex(hex[6:8])} } return color.RGBA{} } func parseHex(s string) uint8 { val, _ := strconv.ParseUint(s, 16, 8) return uint8(val) } // RandColor 生成随机颜色 hex 字符串 func RandColor() string { r := uint8(rand.Int(0, 255)) g := uint8(rand.Int(0, 255)) b := uint8(rand.Int(0, 255)) a := uint8(rand.Int(105, 255)) // 105-255 return fmt.Sprintf("#%02X%02X%02X%02X", r, g, b, a) }