style.go 858 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package svg
  2. import "encoding/xml"
  3. import "strings"
  4. import "image/color"
  5. import "github.com/mazznoer/csscolorparser"
  6. type Style map[string]string
  7. func ParseStyle(str string) (Style, error) {
  8. res := make(Style)
  9. rules := strings.Split(";", str)
  10. for _, rule := range rules {
  11. parts := strings.SplitN(rule, ":", 2)
  12. key := parts[0]
  13. value := "true"
  14. if len(parts) > 1 {
  15. value = parts[1]
  16. }
  17. res[key] = value
  18. }
  19. return res, nil
  20. }
  21. func (s *Style) UnmarshalXMLAttr(attr xml.Attr) error {
  22. style, err := ParseStyle(attr.Value)
  23. if err != nil {
  24. return err
  25. }
  26. *s = style
  27. return nil
  28. }
  29. var _ xml.UnmarshalerAttr = &Style{}
  30. func (s *Style) ToColor(key string) color.Color {
  31. name, ok := s[key]
  32. if !ok {
  33. return color.RGBA{254, 0, 0, 255}
  34. }
  35. c, err := csscolorparser.Parse(name)
  36. if err != nil {
  37. return color.RGBA{253, 0, 0, 255}
  38. }
  39. return c
  40. }