Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Color constructors taking integer arguments (fixes #123) #124

Merged
merged 2 commits into from May 11, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 34 additions & 0 deletions src/graphics/color.rs
Expand Up @@ -26,6 +26,25 @@ impl Color {
pub fn rgba(r: f32, g: f32, b: f32, a: f32) -> Color {
Color { r, g, b, a }
}

/// Creates a new `Color`, with the specified RGB integer values and the alpha set to 1.0.
pub fn rgb8(r: u8, g: u8, b: u8) -> Color {
let r = f32::from(r) / 255.0;
let g = f32::from(g) / 255.0;
let b = f32::from(b) / 255.0;

Color { r, g, b, a: 1.0 }
}

/// Creates a new `Color`, with the specified RGBA integer values.
pub fn rgba8(r: u8, g: u8, b: u8, a: u8) -> Color {
let r = f32::from(r) / 255.0;
let g = f32::from(g) / 255.0;
let b = f32::from(b) / 255.0;
let a = f32::from(a) / 255.0;

Color { r, g, b, a }
}
}

/// Shortcut for Color::rgb(0.0, 0.0, 0.0).
Expand All @@ -43,3 +62,18 @@ pub const WHITE: Color = Color {
b: 1.0,
a: 1.0,
};

#[cfg(test)]
mod tests {
use super::Color;

#[test]
fn rgb8_creation() {
let c1 = Color::rgb8(100, 149, 236);
let c2 = Color::rgb(0.39, 0.58, 0.92);

assert!((c1.r - c2.r).abs() < 0.01);
assert!((c1.g - c2.g).abs() < 0.01);
assert!((c1.b - c2.b).abs() < 0.01);
}
}