pub struct Sprite<'s> { /* private fields */ }
Expand description
Drawable representation of a texture
Sprite is a drawable type that allows to easily
display a Texture
(or a part of it) on a render target.
Note:
Currently, it is not feasible to store sprites long term.
A common pattern with rust-sfml is to create a Sprite
right before you start drawing,
and draw all the sprites you want with it. You can change its properties using
set_texture
, set_position
, etc., before drawing it, as many times as you need to.
Implementations§
Source§impl<'s> Sprite<'s>
impl<'s> Sprite<'s>
Sourcepub fn new() -> Sprite<'s>
pub fn new() -> Sprite<'s>
Examples found in repository?
More examples
12fn main() -> SfResult<()> {
13 example_ensure_right_working_dir();
14
15 let mut window = RenderWindow::new(
16 (800, 600),
17 "Borrowed resources",
18 Style::CLOSE,
19 &Default::default(),
20 )?;
21 window.set_vertical_sync_enabled(true);
22
23 // Create a new texture. (Hey Frank!)
24 let frank = Texture::from_file("frank.jpeg")?;
25
26 // Create a font.
27 let font = Font::from_file("sansation.ttf")?;
28
29 // Create a circle with the Texture.
30 let mut circle = CircleShape::with_texture(&frank);
31 circle.set_radius(70.0);
32 circle.set_position((100.0, 100.0));
33
34 // Create a Sprite.
35 let mut sprite = Sprite::new();
36 // Have it use the same texture as the circle.
37 sprite.set_texture(&frank, true);
38 sprite.set_position((400.0, 300.0));
39 sprite.set_scale(0.5);
40
41 // Create a ConvexShape using the same texture.
42 let mut convex_shape = ConvexShape::with_texture(6, &frank);
43 convex_shape.set_point(0, (400., 100.));
44 convex_shape.set_point(1, (500., 70.));
45 convex_shape.set_point(2, (450., 100.));
46 convex_shape.set_point(3, (580., 150.));
47 convex_shape.set_point(4, (420., 230.));
48 convex_shape.set_point(5, (420., 120.));
49
50 // Create an initialized text using the font.
51 let title = Text::new("Borrowed resources example!", &font, 50);
52
53 // Create a second text using the same font.
54 // This time, we create and initialize it separately.
55 let mut second_text = Text::default();
56 second_text.set_string("This text shares the same font with the title!");
57 second_text.set_font(&font);
58 second_text.set_fill_color(Color::GREEN);
59 second_text.set_position((10.0, 350.0));
60 second_text.set_character_size(20);
61
62 // Create a third text using the same font.
63 let mut third_text = Text::new("This one too!", &font, 20);
64 third_text.set_position((300.0, 100.0));
65 third_text.set_fill_color(Color::RED);
66
67 'mainloop: loop {
68 while let Some(event) = window.poll_event() {
69 match event {
70 Event::Closed
71 | Event::KeyPressed {
72 code: Key::Escape, ..
73 } => break 'mainloop,
74 _ => {}
75 }
76 }
77
78 window.clear(Color::BLACK);
79 window.draw(&circle);
80 window.draw(&sprite);
81 window.draw(&convex_shape);
82 window.draw(&title);
83 window.draw(&second_text);
84 window.draw(&third_text);
85
86 // Little test here for `Shape::points`
87 let mut circ = CircleShape::new(4.0, 30);
88 circ.set_origin(2.0);
89 circ.set_fill_color(Color::YELLOW);
90
91 for p in convex_shape.points() {
92 circ.set_position(p);
93 window.draw(&circ);
94 }
95
96 window.display();
97 }
98 Ok(())
99}
Sourcepub fn with_texture(texture: &'s Texture) -> Sprite<'s>
pub fn with_texture(texture: &'s Texture) -> Sprite<'s>
Create a new sprite with a texture
Examples found in repository?
191 fn new(bg_texture: &'t Texture, entity_texture: &'t Texture) -> SfResult<Self> {
192 let mut surface = RenderTexture::new(800, 600)?;
193 surface.set_smooth(true);
194 let mut bg_sprite = Sprite::with_texture(bg_texture);
195 bg_sprite.set_position((135., 100.));
196 let mut entities = Vec::new();
197
198 for i in 0..6 {
199 entities.push(Sprite::with_texture_and_rect(
200 entity_texture,
201 IntRect::new(96 * i, 0, 96, 96),
202 ));
203 }
204
205 let mut shader = Shader::from_file("edge.frag", ShaderType::Fragment)?;
206 shader.set_uniform_current_texture("texture")?;
207
208 Ok(Self {
209 surface,
210 bg_sprite,
211 entities,
212 shader,
213 })
214 }
215}
216
217impl Drawable for Edge<'_> {
218 fn draw<'a: 'shader, 'texture, 'shader, 'shader_texture>(
219 &'a self,
220 target: &mut dyn RenderTarget,
221 states: &RenderStates<'texture, 'shader, 'shader_texture>,
222 ) {
223 let mut states = *states;
224 states.shader = Some(&self.shader);
225 target.draw_with_renderstates(&Sprite::with_texture(self.surface.texture()), &states);
226 }
227}
228
229impl Effect for Edge<'_> {
230 fn update(&mut self, t: f32, x: f32, y: f32) -> SfResult<()> {
231 self.shader
232 .set_uniform_float("edge_threshold", 1. - (x + y) / 2.)?;
233 let entities_len = self.entities.len() as f32;
234
235 for (i, en) in self.entities.iter_mut().enumerate() {
236 let pos = (
237 (0.25 * (t * i as f32 + (entities_len - i as f32))).cos() * 300. + 350.,
238 (0.25 * (t * (entities_len - i as f32) + i as f32)).cos() * 200. + 250.,
239 );
240 en.set_position(pos);
241 }
242 self.surface.clear(Color::WHITE);
243 self.surface.draw(&self.bg_sprite);
244 for en in &self.entities {
245 self.surface.draw(en);
246 }
247 self.surface.display();
248 Ok(())
249 }
250 fn as_drawable(&self) -> &dyn Drawable {
251 self
252 }
253 fn name(&self) -> &str {
254 "edge post-effect"
255 }
256}
257
258fn main() -> SfResult<()> {
259 example_ensure_right_working_dir();
260
261 let mut window = RenderWindow::new(
262 (800, 600),
263 "SFML Shader",
264 Style::TITLEBAR | Style::CLOSE,
265 &Default::default(),
266 )?;
267 window.set_vertical_sync_enabled(true);
268 let font = Font::from_file("sansation.ttf")?;
269 let bg = Texture::from_file("background.jpg")?;
270 let mut bg_texture = Texture::from_file("sfml.png")?;
271 bg_texture.set_smooth(true);
272 let mut entity_texture = Texture::from_file("devices.png")?;
273 entity_texture.set_smooth(true);
274 let effects: [&mut dyn Effect; 4] = [
275 &mut Pixelate::new(&bg)?,
276 &mut WaveBlur::new(&font)?,
277 &mut StormBlink::new()?,
278 &mut Edge::new(&bg_texture, &entity_texture)?,
279 ];
280 let mut current = 0;
281 let text_bg_texture = Texture::from_file("text-background.png")?;
282 let mut text_bg = Sprite::with_texture(&text_bg_texture);
283 text_bg.set_position((0., 520.));
284 text_bg.set_color(Color::rgba(255, 255, 255, 200));
285 let msg = format!("Current effect: {}", effects[current].name());
286 let mut desc = Text::new(&msg, &font, 20);
287 desc.set_position((10., 530.));
288 desc.set_fill_color(Color::rgb(80, 80, 80));
289 let msg = "Press left and right arrows to change the current shader";
290 let mut instructions = Text::new(msg, &font, 20);
291 instructions.set_position((280., 555.));
292 instructions.set_fill_color(Color::rgb(80, 80, 80));
293 let clock = Clock::start()?;
294
295 while window.is_open() {
296 while let Some(event) = window.poll_event() {
297 use crate::Event::*;
298 match event {
299 Closed => window.close(),
300 KeyPressed { code, .. } => match code {
301 Key::Escape => window.close(),
302 Key::Left => {
303 if current == 0 {
304 current = effects.len() - 1;
305 } else {
306 current -= 1;
307 }
308 desc.set_string(&format!("Current effect: {}", effects[current].name()));
309 }
310 Key::Right => {
311 if current == effects.len() - 1 {
312 current = 0;
313 } else {
314 current += 1;
315 }
316 desc.set_string(&format!("Current effect: {}", effects[current].name()));
317 }
318 _ => {}
319 },
320 _ => {}
321 }
322 }
323
324 let x = window.mouse_position().x as f32 / window.size().x as f32;
325 let y = window.mouse_position().y as f32 / window.size().y as f32;
326
327 effects[current].update(clock.elapsed_time().as_seconds(), x, y)?;
328
329 window.clear(Color::rgb(255, 128, 0));
330 window.draw(effects[current].as_drawable());
331 window.draw(&text_bg);
332 window.draw(&instructions);
333 window.draw(&desc);
334 window.display();
335 }
336 Ok(())
337}
More examples
55fn main() -> SfResult<()> {
56 example_ensure_right_working_dir();
57
58 let mut tex_holder = ResourceHolder::<Texture, _>::default();
59 tex_holder.load("frank", "frank.jpeg")?;
60 let mut sb_holder = ResourceHolder::<SoundBuffer, _>::default();
61 sb_holder.load("canary", "canary.wav")?;
62 let mut rw = RenderWindow::new(
63 (800, 600),
64 "Resource holder test",
65 Style::CLOSE,
66 &Default::default(),
67 )?;
68 rw.set_vertical_sync_enabled(true);
69 let mut sound = Sound::with_buffer(sb_holder.get("canary"));
70 sound.play();
71 while rw.is_open() {
72 while let Some(ev) = rw.poll_event() {
73 match ev {
74 Event::Closed
75 | Event::KeyPressed {
76 code: Key::Escape, ..
77 } => rw.close(),
78 _ => {}
79 }
80 }
81 rw.clear(Color::BLACK);
82 rw.draw(&Sprite::with_texture(tex_holder.get("frank")));
83 rw.display();
84 }
85 Ok(())
86}
121fn main() -> SfResult<()> {
122 example_ensure_right_working_dir();
123
124 let mut window =
125 RenderWindow::new((800, 600), "SFML window", Style::CLOSE, &Default::default())?;
126 window.set_framerate_limit(60);
127
128 // Create a new texture.
129 let texture = RcTexture::from_file("logo.png")?;
130 let texture2 = test_getting_rc_texture_from_texture()?;
131
132 // Create a new font.
133 let font_path = match std::env::args().nth(1) {
134 Some(path) => path,
135 None => "sansation.ttf".into(),
136 };
137 let mut font = RcFont::from_file(&font_path)?;
138
139 // Load many resources with no lifetime contingencies
140 let mut floating_resources = Vec::from([
141 FloatingResource::with_texture(&texture2, true, true, 1.1f32),
142 FloatingResource::with_texture(&texture2, true, true, 1.2f32),
143 FloatingResource::with_texture(&texture, true, true, 1f32),
144 FloatingResource::with_texture(&texture, true, false, 1.5f32),
145 FloatingResource::with_texture(&texture, false, true, 2f32),
146 FloatingResource::with_texture(&texture, false, false, 2.5f32),
147 FloatingResource::with_font(&font, true, true, 1.25f32),
148 FloatingResource::with_font(&font, true, true, 1.75f32),
149 FloatingResource::with_font(&font, true, true, 2.25f32),
150 FloatingResource::with_font(&font, true, true, 2.75f32),
151 ]);
152
153 let set_smooth_text = get_set_smooth_rc_text(&font);
154 let mut show_texture_atlas = false;
155 let mut text_buf = String::from("SFML");
156
157 while window.is_open() {
158 while let Some(event) = window.poll_event() {
159 if event == Event::Closed {
160 window.close();
161 }
162
163 match event {
164 Event::Closed => window.close(),
165 Event::KeyPressed { code, ctrl, .. } => match code {
166 Key::S => {
167 let smooth = !font.is_smooth();
168 font.set_smooth(smooth);
169 }
170 Key::T => {
171 show_texture_atlas ^= true;
172 }
173 Key::V if ctrl => {
174 text_buf.push_str(&clipboard::get_string());
175 }
176 _ => {}
177 },
178 Event::TextEntered { unicode } if show_texture_atlas => {
179 if unicode == 0x8 as char {
180 text_buf.pop();
181 } else if !unicode.is_ascii_control() && unicode != 's' && unicode != 't' {
182 text_buf.push(unicode);
183 }
184 }
185 _ => {}
186 }
187 }
188
189 // Update floating_resource positions so they move around on the screen
190 for floating_resource in &mut floating_resources {
191 floating_resource.move_resources(Vector2f::new(800f32, 600f32));
192 floating_resource.text.set_string(&text_buf);
193 }
194
195 window.clear(Color::BLACK);
196
197 // Fetch and draw all the sprites in floating_resources
198 for floating_resource in &floating_resources {
199 floating_resource.render(&mut window);
200 }
201
202 window.draw(&set_smooth_text);
203 if show_texture_atlas {
204 let scale = 3.0;
205 let tex = font.texture(16);
206 let mut rs = RectangleShape::with_size(tex.size().as_other());
207 rs.set_fill_color(Color::MAGENTA);
208 rs.set_scale(scale);
209 window.draw(&rs);
210 let mut s = Sprite::with_texture(&*tex);
211 s.set_scale(scale);
212 window.draw(&s);
213 }
214 window.display();
215 }
216 Ok(())
217}
16fn main() -> SfResult<()> {
17 example_ensure_right_working_dir();
18
19 let mut exit = false;
20 let mut srgb = false;
21
22 while !exit {
23 let ctx_sett = ContextSettings {
24 depth_bits: 24,
25 srgb_capable: srgb,
26 ..Default::default()
27 };
28
29 let mut window = RenderWindow::new(
30 (800, 600),
31 "SFML graphics with OpenGL",
32 Style::default(),
33 &ctx_sett,
34 )?;
35 window.set_vertical_sync_enabled(true);
36
37 let mut bg_tex = Texture::new()?;
38 bg_tex.set_srgb(srgb);
39 bg_tex.load_from_file("opengl-background.jpg", IntRect::default())?;
40 let bg_sprite = Sprite::with_texture(&bg_tex);
41
42 let font = Font::from_file("sansation.ttf")?;
43 let mut text = Text::new("SFML / OpenGL demo", &font, 32);
44 let mut srgb_instr = Text::new("Press space to toggle sRGB conversion", &font, 32);
45 let mut mipmap_instr = Text::new("Press return to toggle mipmapping", &font, 32);
46 text.set_fill_color(Color::rgba(255, 255, 255, 170));
47 srgb_instr.set_fill_color(Color::rgba(255, 255, 255, 170));
48 mipmap_instr.set_fill_color(Color::rgba(255, 255, 255, 170));
49 text.set_position((250., 450.));
50 srgb_instr.set_position((150., 500.));
51 mipmap_instr.set_position((180., 550.));
52
53 let mut texture = Texture::from_file("texture.jpg")?;
54 texture.generate_mipmap()?;
55 window.set_active(true)?;
56 unsafe {
57 gl::glEnable(gl::GL_DEPTH_TEST);
58 gl::glDepthMask(gl::GL_TRUE as _);
59 gl::glClearDepth(1.);
60 gl::glDisable(gl::GL_LIGHTING);
61 gl::glViewport(0, 0, window.size().x as _, window.size().y as _);
62 gl::glMatrixMode(gl::GL_PROJECTION);
63 gl::glLoadIdentity();
64 let ratio = (window.size().x / window.size().y) as gl::GLdouble;
65 gl::glFrustum(-ratio, ratio, -1., 1., 1., 500.);
66 gl::glEnable(gl::GL_TEXTURE_2D);
67 Texture::bind(&texture);
68 }
69
70 let cube: [f32; 180] = [
71 -20., -20., -20., 0., 0., -20., 20., -20., 1., 0., -20., -20., 20., 0., 1., -20., -20.,
72 20., 0., 1., -20., 20., -20., 1., 0., -20., 20., 20., 1., 1., 20., -20., -20., 0., 0.,
73 20., 20., -20., 1., 0., 20., -20., 20., 0., 1., 20., -20., 20., 0., 1., 20., 20., -20.,
74 1., 0., 20., 20., 20., 1., 1., -20., -20., -20., 0., 0., 20., -20., -20., 1., 0., -20.,
75 -20., 20., 0., 1., -20., -20., 20., 0., 1., 20., -20., -20., 1., 0., 20., -20., 20.,
76 1., 1., -20., 20., -20., 0., 0., 20., 20., -20., 1., 0., -20., 20., 20., 0., 1., -20.,
77 20., 20., 0., 1., 20., 20., -20., 1., 0., 20., 20., 20., 1., 1., -20., -20., -20., 0.,
78 0., 20., -20., -20., 1., 0., -20., 20., -20., 0., 1., -20., 20., -20., 0., 1., 20.,
79 -20., -20., 1., 0., 20., 20., -20., 1., 1., -20., -20., 20., 0., 0., 20., -20., 20.,
80 1., 0., -20., 20., 20., 0., 1., -20., 20., 20., 0., 1., 20., -20., 20., 1., 0., 20.,
81 20., 20., 1., 1.,
82 ];
83
84 unsafe {
85 gl::glEnableClientState(gl::GL_VERTEX_ARRAY);
86 gl::glEnableClientState(gl::GL_TEXTURE_COORD_ARRAY);
87 gl::glVertexPointer(
88 3,
89 gl::GL_FLOAT,
90 5 * size_of::<gl::GLfloat>() as i32,
91 cube.as_ptr() as *const c_void,
92 );
93 gl::glTexCoordPointer(
94 2,
95 gl::GL_FLOAT,
96 5 * size_of::<gl::GLfloat>() as i32,
97 cube.as_ptr().offset(3) as *const c_void,
98 );
99
100 // Disable normal and color vertex components
101 gl::glDisableClientState(gl::GL_NORMAL_ARRAY);
102 gl::glDisableClientState(gl::GL_COLOR_ARRAY);
103 }
104
105 window.set_active(false)?;
106 let clock = Clock::start()?;
107 let mut mipmap_enabled = true;
108
109 while window.is_open() {
110 while let Some(event) = window.poll_event() {
111 match event {
112 Event::Closed
113 | Event::KeyPressed {
114 code: Key::Escape, ..
115 } => {
116 exit = true;
117 window.close();
118 }
119 Event::KeyPressed {
120 code: Key::Enter, ..
121 } => {
122 if mipmap_enabled {
123 texture = Texture::from_file("texture.jpg")?;
124 mipmap_enabled = false;
125 window.set_active(true)?;
126 Texture::bind(&texture);
127 window.set_active(false)?;
128 } else {
129 texture.generate_mipmap()?;
130 mipmap_enabled = true;
131 }
132 }
133 Event::KeyPressed {
134 code: Key::Space, ..
135 } => {
136 srgb = !srgb;
137 window.close();
138 }
139 Event::Resized { width, height } => {
140 window.set_active(true)?;
141 unsafe {
142 gl::glViewport(0, 0, width as _, height as _);
143 }
144 window.set_active(false)?;
145 }
146 _ => {}
147 }
148 }
149 window.push_gl_states();
150 window.draw(&bg_sprite);
151 window.pop_gl_states();
152
153 if let Err(e) = window.set_active(true) {
154 eprintln!("Failed to set window as active: {e}");
155 }
156
157 unsafe {
158 gl::glClear(gl::GL_DEPTH_BUFFER_BIT);
159 let x: f32 =
160 window.mouse_position().x as f32 * 200. / window.size().x as f32 - 100.;
161 let y: f32 =
162 -window.mouse_position().y as f32 * 200. / window.size().y as f32 + 100.;
163
164 gl::glMatrixMode(gl::GL_MODELVIEW);
165 gl::glLoadIdentity();
166 gl::glTranslatef(x, y, -100.);
167 gl::glRotatef(clock.elapsed_time().as_seconds() * 50., 1., 0., 0.);
168 gl::glRotatef(clock.elapsed_time().as_seconds() * 30., 0., 1., 0.);
169 gl::glRotatef(clock.elapsed_time().as_seconds() * 90., 0., 0., 1.);
170 gl::glDrawArrays(gl::GL_TRIANGLES, 0, 36);
171 }
172 if let Err(e) = window.set_active(false) {
173 eprintln!("Failed to set window as active: {e}");
174 }
175 window.push_gl_states();
176 window.draw(&text);
177 window.draw(&srgb_instr);
178 window.draw(&mipmap_instr);
179 window.pop_gl_states();
180 window.display();
181 }
182 }
183 Ok(())
184}
Sourcepub fn with_texture_and_rect(texture: &'s Texture, rect: IntRect) -> Self
pub fn with_texture_and_rect(texture: &'s Texture, rect: IntRect) -> Self
Create a new sprite with a texture and a source rectangle
Examples found in repository?
191 fn new(bg_texture: &'t Texture, entity_texture: &'t Texture) -> SfResult<Self> {
192 let mut surface = RenderTexture::new(800, 600)?;
193 surface.set_smooth(true);
194 let mut bg_sprite = Sprite::with_texture(bg_texture);
195 bg_sprite.set_position((135., 100.));
196 let mut entities = Vec::new();
197
198 for i in 0..6 {
199 entities.push(Sprite::with_texture_and_rect(
200 entity_texture,
201 IntRect::new(96 * i, 0, 96, 96),
202 ));
203 }
204
205 let mut shader = Shader::from_file("edge.frag", ShaderType::Fragment)?;
206 shader.set_uniform_current_texture("texture")?;
207
208 Ok(Self {
209 surface,
210 bg_sprite,
211 entities,
212 shader,
213 })
214 }
Sourcepub fn set_texture(&mut self, texture: &'s Texture, reset_rect: bool)
pub fn set_texture(&mut self, texture: &'s Texture, reset_rect: bool)
Change the source texture of a sprite
The texture argument refers to a texture that must
exist as long as the sprite uses it. Indeed, the sprite
doesn’t store its own copy of the texture, but rather keeps
a pointer to the one that you passed to this function.
If the source texture is destroyed and the sprite tries to
use it, the behaviour is undefined.
If reset_rect
is true, the texture_rect
property of
the sprite is automatically adjusted to the size of the new
texture. If it is false, the texture rect is left unchanged.
§Arguments
texture
- New texturereset_rect
- Should the texture rect be reset to the size of the new texture?
Examples found in repository?
More examples
12fn main() -> SfResult<()> {
13 example_ensure_right_working_dir();
14
15 let mut window = RenderWindow::new(
16 (800, 600),
17 "Borrowed resources",
18 Style::CLOSE,
19 &Default::default(),
20 )?;
21 window.set_vertical_sync_enabled(true);
22
23 // Create a new texture. (Hey Frank!)
24 let frank = Texture::from_file("frank.jpeg")?;
25
26 // Create a font.
27 let font = Font::from_file("sansation.ttf")?;
28
29 // Create a circle with the Texture.
30 let mut circle = CircleShape::with_texture(&frank);
31 circle.set_radius(70.0);
32 circle.set_position((100.0, 100.0));
33
34 // Create a Sprite.
35 let mut sprite = Sprite::new();
36 // Have it use the same texture as the circle.
37 sprite.set_texture(&frank, true);
38 sprite.set_position((400.0, 300.0));
39 sprite.set_scale(0.5);
40
41 // Create a ConvexShape using the same texture.
42 let mut convex_shape = ConvexShape::with_texture(6, &frank);
43 convex_shape.set_point(0, (400., 100.));
44 convex_shape.set_point(1, (500., 70.));
45 convex_shape.set_point(2, (450., 100.));
46 convex_shape.set_point(3, (580., 150.));
47 convex_shape.set_point(4, (420., 230.));
48 convex_shape.set_point(5, (420., 120.));
49
50 // Create an initialized text using the font.
51 let title = Text::new("Borrowed resources example!", &font, 50);
52
53 // Create a second text using the same font.
54 // This time, we create and initialize it separately.
55 let mut second_text = Text::default();
56 second_text.set_string("This text shares the same font with the title!");
57 second_text.set_font(&font);
58 second_text.set_fill_color(Color::GREEN);
59 second_text.set_position((10.0, 350.0));
60 second_text.set_character_size(20);
61
62 // Create a third text using the same font.
63 let mut third_text = Text::new("This one too!", &font, 20);
64 third_text.set_position((300.0, 100.0));
65 third_text.set_fill_color(Color::RED);
66
67 'mainloop: loop {
68 while let Some(event) = window.poll_event() {
69 match event {
70 Event::Closed
71 | Event::KeyPressed {
72 code: Key::Escape, ..
73 } => break 'mainloop,
74 _ => {}
75 }
76 }
77
78 window.clear(Color::BLACK);
79 window.draw(&circle);
80 window.draw(&sprite);
81 window.draw(&convex_shape);
82 window.draw(&title);
83 window.draw(&second_text);
84 window.draw(&third_text);
85
86 // Little test here for `Shape::points`
87 let mut circ = CircleShape::new(4.0, 30);
88 circ.set_origin(2.0);
89 circ.set_fill_color(Color::YELLOW);
90
91 for p in convex_shape.points() {
92 circ.set_position(p);
93 window.draw(&circ);
94 }
95
96 window.display();
97 }
98 Ok(())
99}
Sourcepub fn set_color(&mut self, color: Color)
pub fn set_color(&mut self, color: Color)
Set the global color of a sprite
This color is modulated (multiplied) with the sprite’s texture. It can be used to colorize the sprite, or change its global opacity. By default, the sprite’s color is opaque white.
§Arguments
- color - New color of the sprite
Examples found in repository?
258fn main() -> SfResult<()> {
259 example_ensure_right_working_dir();
260
261 let mut window = RenderWindow::new(
262 (800, 600),
263 "SFML Shader",
264 Style::TITLEBAR | Style::CLOSE,
265 &Default::default(),
266 )?;
267 window.set_vertical_sync_enabled(true);
268 let font = Font::from_file("sansation.ttf")?;
269 let bg = Texture::from_file("background.jpg")?;
270 let mut bg_texture = Texture::from_file("sfml.png")?;
271 bg_texture.set_smooth(true);
272 let mut entity_texture = Texture::from_file("devices.png")?;
273 entity_texture.set_smooth(true);
274 let effects: [&mut dyn Effect; 4] = [
275 &mut Pixelate::new(&bg)?,
276 &mut WaveBlur::new(&font)?,
277 &mut StormBlink::new()?,
278 &mut Edge::new(&bg_texture, &entity_texture)?,
279 ];
280 let mut current = 0;
281 let text_bg_texture = Texture::from_file("text-background.png")?;
282 let mut text_bg = Sprite::with_texture(&text_bg_texture);
283 text_bg.set_position((0., 520.));
284 text_bg.set_color(Color::rgba(255, 255, 255, 200));
285 let msg = format!("Current effect: {}", effects[current].name());
286 let mut desc = Text::new(&msg, &font, 20);
287 desc.set_position((10., 530.));
288 desc.set_fill_color(Color::rgb(80, 80, 80));
289 let msg = "Press left and right arrows to change the current shader";
290 let mut instructions = Text::new(msg, &font, 20);
291 instructions.set_position((280., 555.));
292 instructions.set_fill_color(Color::rgb(80, 80, 80));
293 let clock = Clock::start()?;
294
295 while window.is_open() {
296 while let Some(event) = window.poll_event() {
297 use crate::Event::*;
298 match event {
299 Closed => window.close(),
300 KeyPressed { code, .. } => match code {
301 Key::Escape => window.close(),
302 Key::Left => {
303 if current == 0 {
304 current = effects.len() - 1;
305 } else {
306 current -= 1;
307 }
308 desc.set_string(&format!("Current effect: {}", effects[current].name()));
309 }
310 Key::Right => {
311 if current == effects.len() - 1 {
312 current = 0;
313 } else {
314 current += 1;
315 }
316 desc.set_string(&format!("Current effect: {}", effects[current].name()));
317 }
318 _ => {}
319 },
320 _ => {}
321 }
322 }
323
324 let x = window.mouse_position().x as f32 / window.size().x as f32;
325 let y = window.mouse_position().y as f32 / window.size().y as f32;
326
327 effects[current].update(clock.elapsed_time().as_seconds(), x, y)?;
328
329 window.clear(Color::rgb(255, 128, 0));
330 window.draw(effects[current].as_drawable());
331 window.draw(&text_bg);
332 window.draw(&instructions);
333 window.draw(&desc);
334 window.display();
335 }
336 Ok(())
337}
Sourcepub fn texture(&self) -> Option<&'s Texture>
pub fn texture(&self) -> Option<&'s Texture>
Get the source texture of a sprite
If the sprite has no source texture, None is returned. You can’t modify the texture when you retrieve it with this function.
Return an Option to the sprite’s texture
Sourcepub fn color(&self) -> Color
pub fn color(&self) -> Color
Get the global color of a sprite
Return the global color of the sprite
Sourcepub fn local_bounds(&self) -> FloatRect
pub fn local_bounds(&self) -> FloatRect
Get the local bounding rectangle of a sprite
The returned rectangle is in local coordinates, which means that it ignores the transformations (translation, rotation, scale, …) that are applied to the entity. In other words, this function returns the bounds of the entity in the entity’s coordinate system.
Return the local bounding rectangle of the entity
Sourcepub fn global_bounds(&self) -> FloatRect
pub fn global_bounds(&self) -> FloatRect
Get the global bounding rectangle of a sprite
The returned rectangle is in global coordinates, which means that it takes in account the transformations (translation, rotation, scale, …) that are applied to the entity. In other words, this function returns the bounds of the sprite in the global 2D world’s coordinate system.
Return the global bounding rectangle of the entity
Sourcepub fn texture_rect(&self) -> IntRect
pub fn texture_rect(&self) -> IntRect
Get the sub-rectangle of the texture displayed by a sprite
Return the texture rectangle of the sprite
Sourcepub fn set_texture_rect(&mut self, rect: IntRect)
pub fn set_texture_rect(&mut self, rect: IntRect)
Set the sub-rectangle of the texture that a sprite will display
The texture rect is useful when you don’t want to display the whole texture, but rather a part of it. By default, the texture rect covers the entire texture.
§Arguments
- rectangle - Rectangle defining the region of the texture to display