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 public final int red; 014 public final int green; 015 public final int blue; 016 017 /** Constructs a default color (black). */ 018 public Color8Bit() { 019 red = 0; 020 green = 0; 021 blue = 0; 022 } 023 024 /** 025 * Constructs a Color8Bit. 026 * 027 * @param red Red value (0-255) 028 * @param green Green value (0-255) 029 * @param blue Blue value (0-255) 030 */ 031 public Color8Bit(int red, int green, int blue) { 032 this.red = MathUtil.clamp(red, 0, 255); 033 this.green = MathUtil.clamp(green, 0, 255); 034 this.blue = MathUtil.clamp(blue, 0, 255); 035 } 036 037 /** 038 * Constructs a Color8Bit from a Color. 039 * 040 * @param color The color 041 */ 042 public Color8Bit(Color color) { 043 this((int) (color.red * 255), (int) (color.green * 255), (int) (color.blue * 255)); 044 } 045 046 /** 047 * Constructs a Color8Bit from a hex string. 048 * 049 * @param hexString a string of the format <code>#RRGGBB</code> 050 * @throws IllegalArgumentException if the hex string is invalid. 051 */ 052 public Color8Bit(String hexString) { 053 if (hexString.length() != 7 || !hexString.startsWith("#")) { 054 throw new IllegalArgumentException("Invalid hex string \"" + hexString + "\""); 055 } 056 057 this.red = Integer.valueOf(hexString.substring(1, 3), 16); 058 this.green = Integer.valueOf(hexString.substring(3, 5), 16); 059 this.blue = Integer.valueOf(hexString.substring(5, 7), 16); 060 } 061 062 @Override 063 public boolean equals(Object other) { 064 if (this == other) { 065 return true; 066 } 067 if (other == null || getClass() != other.getClass()) { 068 return false; 069 } 070 071 Color8Bit color8Bit = (Color8Bit) other; 072 return red == color8Bit.red && green == color8Bit.green && blue == color8Bit.blue; 073 } 074 075 @Override 076 public int hashCode() { 077 return Objects.hash(red, green, blue); 078 } 079 080 @Override 081 public String toString() { 082 return toHexString(); 083 } 084 085 /** 086 * Return this color represented as a hex string. 087 * 088 * @return a string of the format <code>#RRGGBB</code> 089 */ 090 public String toHexString() { 091 return String.format("#%02X%02X%02X", red, green, blue); 092 } 093}