Color.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #pragma once
  2. #include <AK/Types.h>
  3. typedef dword RGBA32;
  4. inline constexpr dword make_rgb(byte r, byte g, byte b)
  5. {
  6. return ((r << 16) | (g << 8) | b);
  7. }
  8. class Color {
  9. public:
  10. enum NamedColor {
  11. Black,
  12. White,
  13. Red,
  14. Green,
  15. Blue,
  16. Yellow,
  17. Magenta,
  18. DarkGray,
  19. MidGray,
  20. LightGray,
  21. };
  22. Color() { }
  23. Color(NamedColor);
  24. Color(byte r, byte g, byte b) : m_value(0xff000000 | (r << 16) | (g << 8) | b) { }
  25. Color(byte r, byte g, byte b, byte a) : m_value((a << 24) | (r << 16) | (g << 8) | b) { }
  26. static Color from_rgb(unsigned rgb) { return Color(rgb | 0xff000000); }
  27. static Color from_rgba(unsigned rgba) { return Color(rgba); }
  28. byte red() const { return (m_value >> 16) & 0xff; }
  29. byte green() const { return (m_value >> 8) & 0xff; }
  30. byte blue() const { return m_value & 0xff; }
  31. byte alpha() const { return (m_value >> 24) & 0xff; }
  32. void set_alpha(byte value)
  33. {
  34. m_value &= 0x00ffffff;
  35. m_value |= value << 24;
  36. }
  37. Color with_alpha(byte alpha)
  38. {
  39. return Color((m_value & 0x00ffffff) | alpha << 24);
  40. }
  41. Color blend(Color source) const
  42. {
  43. if (!alpha() || source.alpha() == 255)
  44. return source;
  45. if (!source.alpha())
  46. return *this;
  47. int d = 255 * (alpha() + source.alpha()) - alpha() * source.alpha();
  48. byte r = (red() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.red()) / d;
  49. byte g = (green() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.green()) / d;
  50. byte b = (blue() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.blue()) / d;
  51. byte a = d / 255;
  52. return Color(r, g, b, a);
  53. }
  54. RGBA32 value() const { return m_value; }
  55. private:
  56. explicit Color(RGBA32 rgba) : m_value(rgba) { }
  57. RGBA32 m_value { 0 };
  58. };