feat(widget): add circle widget (#159)

This commit is contained in:
FujiApple 2023-05-10 01:56:35 +08:00 committed by GitHub
parent 548961f610
commit c7aca64ba1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 71 additions and 1 deletions

View file

@ -5,7 +5,7 @@ use ratatui::{
style::{Color, Modifier, Style},
symbols,
text::{Span, Spans},
widgets::canvas::{Canvas, Line, Map, MapResolution, Rectangle},
widgets::canvas::{Canvas, Circle, Line, Map, MapResolution, Rectangle},
widgets::{
Axis, BarChart, Block, Borders, Cell, Chart, Dataset, Gauge, LineGauge, List, ListItem,
Paragraph, Row, Sparkline, Table, Tabs, Wrap,
@ -346,6 +346,12 @@ where
height: 10.0,
color: Color::Yellow,
});
ctx.draw(&Circle {
x: app.servers[2].coords.1,
y: app.servers[2].coords.0,
radius: 10.0,
color: Color::Green,
});
for (i, s1) in app.servers.iter().enumerate() {
for s2 in &app.servers[i + 1..] {
ctx.draw(&Line {

View file

@ -0,0 +1,62 @@
use crate::{
style::Color,
widgets::canvas::{Painter, Shape},
};
/// Shape to draw a circle with a given center and radius and with the given color
#[derive(Debug, Clone)]
pub struct Circle {
pub x: f64,
pub y: f64,
pub radius: f64,
pub color: Color,
}
impl Shape for Circle {
fn draw(&self, painter: &mut Painter<'_, '_>) {
for angle in 0..360 {
let radians = f64::from(angle).to_radians();
let circle_x = self.radius.mul_add(radians.cos(), self.x);
let circle_y = self.radius.mul_add(radians.sin(), self.y);
if let Some((x, y)) = painter.get_point(circle_x, circle_y) {
painter.paint(x, y, self.color);
}
}
}
}
#[cfg(test)]
mod tests {
use crate::buffer::Buffer;
use crate::layout::Rect;
use crate::style::Color;
use crate::symbols::Marker;
use crate::widgets::canvas::{Canvas, Circle};
use crate::widgets::Widget;
#[test]
fn test_it_draws_a_circle() {
let mut buffer = Buffer::empty(Rect::new(0, 0, 10, 5));
let canvas = Canvas::default()
.paint(|ctx| {
ctx.draw(&Circle {
x: 5.0,
y: 2.0,
radius: 5.0,
color: Color::Reset,
});
})
.marker(Marker::Braille)
.x_bounds([-10.0, 10.0])
.y_bounds([-10.0, 10.0]);
canvas.render(buffer.area, &mut buffer);
let expected = Buffer::with_lines(vec![
" ⢀⣠⢤⣀ ",
" ⢰⠋ ⠈⣇",
" ⠘⣆⡀ ⣠⠇",
" ⠉⠉⠁ ",
" ",
]);
assert_eq!(buffer, expected);
}
}

View file

@ -1,9 +1,11 @@
mod circle;
mod line;
mod map;
mod points;
mod rectangle;
mod world;
pub use self::circle::Circle;
pub use self::line::Line;
pub use self::map::{Map, MapResolution};
pub use self::points::Points;