pushrod/render/canvas_helper.rs
1// Pushrod Rendering Library
2// Canvas Helper Trait
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use crate::render::widget::Widget;
17use crate::render::widget_config::{CONFIG_BORDER_WIDTH, CONFIG_SIZE};
18use crate::render::{SIZE_HEIGHT, SIZE_WIDTH};
19use sdl2::rect::{Point, Rect};
20use sdl2::render::Canvas;
21use sdl2::video::Window;
22
23/// This trait is used in conjunction with `Widget`s or anything else that draws to a `Canvas` object.
24/// It provides convenience methods to provide drawing functions common to `Widget`s. All points and
25/// dimensions are relative to the position of the `Widget`, so no translation is necessary.
26///
27/// To implement this trait in your `Widget`, all you have to do is:
28/// ```ignore
29/// impl CanvasHelper for (myWidget) { }
30/// ```
31pub trait CanvasHelper: Widget {
32 /// Draws a point in the `Canvas`.
33 fn draw_point(&mut self, c: &mut Canvas<Window>, x: i32, y: i32) {
34 let point = Point::new(self.get_config().to_x(x), self.get_config().to_y(y));
35
36 c.draw_point(point).unwrap();
37 }
38
39 /// Draws a box around the bounding area of the `Widget`.
40 fn draw_bounding_box(&mut self, c: &mut Canvas<Window>) {
41 let border = self.get_config().get_numeric(CONFIG_BORDER_WIDTH);
42
43 for i in 0..border {
44 c.draw_rect(Rect::new(
45 self.get_config().to_x(i as i32),
46 self.get_config().to_y(i as i32),
47 self.get_config().get_size(CONFIG_SIZE)[SIZE_WIDTH] - (i * 2) as u32,
48 self.get_config().get_size(CONFIG_SIZE)[SIZE_HEIGHT] - (i * 2) as u32,
49 ))
50 .unwrap();
51 }
52 }
53
54 /// Returns a `Rect` destination object
55 fn get_rect_dest(&mut self) -> Rect {
56 Rect::new(
57 self.get_config().to_x(0),
58 self.get_config().to_y(0),
59 self.get_config().get_size(CONFIG_SIZE)[SIZE_WIDTH],
60 self.get_config().get_size(CONFIG_SIZE)[SIZE_HEIGHT],
61 )
62 }
63}