blob: 252f3a18935fba87acbdfc9b11d50f3f309263f1 [file] [log] [blame]
// Copyright 2024 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#pragma once
#include <math.h>
#include <stdint.h>
#include <cinttypes>
#include <cstdint>
/// @defgroup pw_color
namespace pw::color {
/// @ingroup pw_color
///
/// Base type for rgb8888.
typedef uint32_t color_rgba8888_t;
/// @ingroup pw_color
///
/// Base type for rgb564.
typedef uint16_t color_rgb565_t;
/// @ingroup pw_color
///
/// Class for converting between RGB values, RGB565 and RGBA8888 formats.
class ColorRgba {
public:
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
/// Instantiate from individual red, green and blue unsigned integers. Alpha
/// is set to the max of 255.
ColorRgba(uint8_t red, uint8_t green, uint8_t blue) {
r = red;
g = green;
b = blue;
a = 255;
}
/// Instantiate from individual red, green, blue and alpha unsigned integers.
ColorRgba(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) {
r = red;
g = green;
b = blue;
a = alpha;
}
/// Instantiate from a 16 bit rgb565 value. This will scale each color to 8
/// bits per pixel.
ColorRgba(color_rgb565_t rgb565) {
// Grab the RGB bits
uint8_t ir = (rgb565 & 0xF800) >> 11;
uint8_t ig = (rgb565 & 0x7E0) >> 5;
uint8_t ib = rgb565 & 0x1F;
// Scale RGB values to 8bits each
r = 255 * ir / 31;
g = 255 * ig / 63;
b = 255 * ib / 31;
a = 255;
}
/// Instantiate from a 32 bit rgb8888 value.
ColorRgba(color_rgba8888_t rgba8888) {
a = (rgba8888 & 0xFF000000) >> 24;
b = (rgba8888 & 0xFF0000) >> 16;
g = (rgba8888 & 0xFF00) >> 8;
r = (rgba8888 & 0xFF);
}
/// Return a 16 bit rgb565 value.
color_rgb565_t ToRgb565() {
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | ((b & 0xF8) >> 3);
}
};
} // namespace pw::color