Skip to main content

egui_charts/chart/rendering/
context.rs

1use egui::{Color32, Painter, Rect};
2
3// Re-export ChartMapping as the primary coordinate type
4pub use crate::chart::coords::ChartMapping;
5
6/// Core rendering context containing painter and drawing area
7pub struct RenderContext<'a> {
8    /// Painter used to draw the overlay.
9    pub painter: &'a Painter,
10    /// Screen rectangle available for rendering.
11    pub rect: Rect,
12}
13
14impl<'a> RenderContext<'a> {
15    /// Bind a painter to the rectangle available for rendering.
16    pub fn new(painter: &'a Painter, rect: Rect) -> Self {
17        Self { painter, rect }
18    }
19}
20
21/// Color scheme for rendering chart elements
22#[derive(Debug, Copy, Clone)]
23pub struct StyleColors {
24    pub bullish: Color32,
25    pub bearish: Color32,
26    pub text: Color32,
27    /// Border color for bullish candles (None = same as body)
28    pub bullish_border: Option<Color32>,
29    /// Border color for bearish candles (None = same as body)
30    pub bearish_border: Option<Color32>,
31    /// Wick color for bullish candles (None = same as border/body)
32    pub bullish_wick: Option<Color32>,
33    /// Wick color for bearish candles (None = same as border/body)
34    pub bearish_wick: Option<Color32>,
35    /// Border width for candles (0 = no border)
36    pub candle_border_width: f32,
37}
38
39impl StyleColors {
40    /// Get color based on bar direction
41    pub fn bar_color(&self, is_bullish: bool) -> Color32 {
42        if is_bullish {
43            self.bullish
44        } else {
45            self.bearish
46        }
47    }
48
49    /// Get wick color based on bar direction
50    /// Falls back to border color, then body color
51    pub fn wick_color(&self, is_bullish: bool) -> Color32 {
52        if is_bullish {
53            self.bullish_wick
54                .or(self.bullish_border)
55                .unwrap_or(self.bullish)
56        } else {
57            self.bearish_wick
58                .or(self.bearish_border)
59                .unwrap_or(self.bearish)
60        }
61    }
62
63    /// Get border color based on bar direction
64    /// Falls back to body color if not set
65    pub fn border_color(&self, is_bullish: bool) -> Color32 {
66        if is_bullish {
67            self.bullish_border.unwrap_or(self.bullish)
68        } else {
69            self.bearish_border.unwrap_or(self.bearish)
70        }
71    }
72
73    /// Check if candle borders should be drawn
74    pub fn has_border(&self) -> bool {
75        self.candle_border_width > 0.0
76    }
77}
78
79/// Params for rendering a single bar
80#[derive(Debug, Copy, Clone)]
81pub struct BarRenderParams {
82    pub x: f32,
83    pub width: f32,
84    pub wick_width: f32,
85}
86
87impl BarRenderParams {
88    pub fn new(x: f32, width: f32, wick_width: f32) -> Self {
89        Self {
90            x,
91            width,
92            wick_width,
93        }
94    }
95}