001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.wpilibj.util;
006
007import edu.wpi.first.math.MathUtil;
008import java.util.Objects;
009
010/** Represents colors with 8 bits of precision. */
011@SuppressWarnings("MemberName")
012public class Color8Bit {
013  /** Red component (0-255). */
014  public final int red;
015
016  /** Green component (0-255). */
017  public final int green;
018
019  /** Blue component (0-255). */
020  public final int blue;
021
022  /** Constructs a default color (black). */
023  public Color8Bit() {
024    red = 0;
025    green = 0;
026    blue = 0;
027  }
028
029  /**
030   * Constructs a Color8Bit.
031   *
032   * @param red Red value (0-255)
033   * @param green Green value (0-255)
034   * @param blue Blue value (0-255)
035   */
036  public Color8Bit(int red, int green, int blue) {
037    this.red = MathUtil.clamp(red, 0, 255);
038    this.green = MathUtil.clamp(green, 0, 255);
039    this.blue = MathUtil.clamp(blue, 0, 255);
040  }
041
042  /**
043   * Constructs a Color8Bit from a Color.
044   *
045   * @param color The color
046   */
047  public Color8Bit(Color color) {
048    this((int) (color.red * 255), (int) (color.green * 255), (int) (color.blue * 255));
049  }
050
051  /**
052   * Constructs a Color8Bit from a hex string.
053   *
054   * @param hexString a string of the format <code>#RRGGBB</code>
055   * @throws IllegalArgumentException if the hex string is invalid.
056   */
057  public Color8Bit(String hexString) {
058    if (hexString.length() != 7 || !hexString.startsWith("#")) {
059      throw new IllegalArgumentException("Invalid hex string \"" + hexString + "\"");
060    }
061
062    this.red = Integer.valueOf(hexString.substring(1, 3), 16);
063    this.green = Integer.valueOf(hexString.substring(3, 5), 16);
064    this.blue = Integer.valueOf(hexString.substring(5, 7), 16);
065  }
066
067  @Override
068  public boolean equals(Object other) {
069    if (this == other) {
070      return true;
071    }
072    if (other == null || getClass() != other.getClass()) {
073      return false;
074    }
075
076    Color8Bit color8Bit = (Color8Bit) other;
077    return red == color8Bit.red && green == color8Bit.green && blue == color8Bit.blue;
078  }
079
080  @Override
081  public int hashCode() {
082    return Objects.hash(red, green, blue);
083  }
084
085  @Override
086  public String toString() {
087    return toHexString();
088  }
089
090  /**
091   * Return this color represented as a hex string.
092   *
093   * @return a string of the format <code>#RRGGBB</code>
094   */
095  public String toHexString() {
096    return String.format("#%02X%02X%02X", red, green, blue);
097  }
098}