1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
use iup_sys;
use Element;
#[derive(Debug, Copy, Clone)]
pub struct InPixels<'a, T: 'static>(pub &'a [&'a [T]]);
#[macro_export]
macro_rules! pixels {
( $($row:expr),+, ) => { pixels![ $($row),+ ] };
( $($row:expr),* ) => { $crate::image::InPixels(&[ $(&$row),* ]) };
}
pub trait ImageElement : Element {
type Pixel : 'static + Copy;
fn new<U>(width: u32, height: u32, pixels: U) -> Self where U: AsRef<[Self::Pixel]>;
fn with<'a>(pixels: InPixels<'a, Self::Pixel>) -> Self {
let pixels = pixels.0;
let height = pixels.len();
let width = pixels.first().map(|row| row.len()).unwrap_or(0);
let mut v = Vec::with_capacity(height * width);
for row in pixels.iter() {
assert_eq!(width, row.len());
for &pixel in row.iter() {
v.push(pixel);
}
}
Self::new(width as u32, height as u32, v)
}
}
pub struct Image(*mut iup_sys::Ihandle);
impl Image {
pub fn set_colors<U>(&mut self, colors: U) -> Image where U: AsRef<[(u8, u8, u8)]> {
assert!(colors.as_ref().len() < 256);
for (i, &color) in colors.as_ref().iter().enumerate() {
self.set_attrib_rgb(i.to_string(), color);
}
self.clone()
}
}
impl ImageElement for Image {
type Pixel = u8;
fn new<U>(width: u32, height: u32, pixels: U) -> Image where U: AsRef<[u8]> {
unsafe {
let pixels = pixels.as_ref();
assert_eq!((width * height) as usize, pixels.len());
Image::from_raw(iup_sys::IupImage(width as i32, height as i32, pixels.as_ptr()))
}
}
}
impl_element!(Image, "image");
pub struct ImageRgb(*mut iup_sys::Ihandle);
impl ImageElement for ImageRgb {
type Pixel = (u8, u8, u8);
fn new<U>(width: u32, height: u32, pixels: U) -> ImageRgb where U: AsRef<[(u8, u8, u8)]> {
unsafe {
let pixels = pixels.as_ref();
assert_eq!((width * height) as usize, pixels.len());
ImageRgb::from_raw(iup_sys::IupImageRGB(width as i32, height as i32,
pixels.as_ptr() as *const _))
}
}
}
impl_element!(ImageRgb, "imagergb");
pub struct ImageRgba(*mut iup_sys::Ihandle);
impl ImageElement for ImageRgba {
type Pixel = (u8, u8, u8, u8);
fn new<U>(width: u32, height: u32, pixels: U) -> ImageRgba where U: AsRef<[(u8, u8, u8, u8)]> {
unsafe {
let pixels = pixels.as_ref();
assert_eq!((width * height) as usize, pixels.len());
ImageRgba::from_raw(iup_sys::IupImageRGBA(width as i32, height as i32,
pixels.as_ptr() as *const _))
}
}
}
impl_element!(ImageRgba, "imagergba");