cursive/examples/colors.rs

75 lines
2.1 KiB
Rust
Raw Normal View History

2017-06-14 07:08:58 +00:00
extern crate cursive;
2017-10-12 23:38:55 +00:00
use cursive::theme::{Color, ColorStyle};
2017-06-14 07:08:58 +00:00
use cursive::view::Boxable;
use cursive::views::Canvas;
2018-06-11 06:29:10 +00:00
use cursive::{Cursive, Printer};
2017-06-14 07:08:58 +00:00
2018-01-16 02:55:27 +00:00
// This example will draw a colored square with a gradient.
//
// We'll use a Canvas, which lets us only define a draw method.
//
// We will combine 2 gradients: one for the background,
// and one for the foreground.
//
// Note: color reproduction is not as good on all backends.
// termion can do full 16M true colors, but ncurses is currently limited to
// 256 colors.
2017-06-14 07:08:58 +00:00
fn main() {
2018-06-20 17:28:44 +00:00
// Start as usual
let mut siv = Cursive::default();
2018-06-20 17:28:44 +00:00
siv.add_global_callback('q', |s| s.quit());
2017-06-14 07:08:58 +00:00
2018-06-20 17:28:44 +00:00
// Canvas lets us easily override any method.
// Canvas can have states, but we don't need any here, so we use `()`.
2018-06-16 20:23:09 +00:00
siv.add_layer(Canvas::new(()).with_draw(draw).fixed_size((20, 10)));
2017-06-14 07:08:58 +00:00
siv.run();
}
2017-06-14 07:43:03 +00:00
2018-06-20 17:28:44 +00:00
/// Method used to draw the cube.
///
/// This takes as input the Canvas state and a printer.
2017-09-23 20:43:02 +00:00
fn draw(_: &(), p: &Printer) {
2018-01-16 02:55:27 +00:00
// We use the view size to calibrate the color
2017-06-14 07:43:03 +00:00
let x_max = p.size.x as u8;
let y_max = p.size.y as u8;
2018-06-20 17:28:44 +00:00
// Print each cell individually
2017-06-14 07:43:03 +00:00
for x in 0..x_max {
for y in 0..y_max {
2018-01-16 02:55:27 +00:00
// We'll use a different style for each cell
let style = ColorStyle::new(
front_color(x, y, x_max, y_max),
back_color(x, y, x_max, y_max),
);
2017-06-14 07:43:03 +00:00
2017-10-12 23:38:55 +00:00
p.with_color(style, |printer| {
printer.print((x, y), "+");
});
2017-06-14 07:43:03 +00:00
}
}
}
2018-01-16 02:55:27 +00:00
// Gradient for the front color
fn front_color(x: u8, y: u8, x_max: u8, y_max: u8) -> Color {
2018-06-20 17:28:44 +00:00
// We return a full 24-bits RGB color, but some backends
// will project it to a 256-colors palette.
2018-01-16 02:55:27 +00:00
Color::Rgb(
x * (255 / x_max),
y * (255 / y_max),
(x + 2 * y) * (255 / (x_max + 2 * y_max)),
)
}
// Gradient for the background color
fn back_color(x: u8, y: u8, x_max: u8, y_max: u8) -> Color {
2018-06-20 17:28:44 +00:00
// Let's try to have a gradient in a different direction than the front color.
2018-01-16 02:55:27 +00:00
Color::Rgb(
128 + (2 * y_max + x - 2 * y) * (128 / (x_max + 2 * y_max)),
255 - y * (255 / y_max),
255 - x * (255 / x_max),
)
}