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?
184 fn new(bg_texture: &'t Texture, entity_texture: &'t Texture) -> SfResult<Self> {
185 let mut surface = RenderTexture::new(800, 600)?;
186 surface.set_smooth(true);
187 let mut bg_sprite = Sprite::with_texture(bg_texture);
188 bg_sprite.set_position((135., 100.));
189 let mut entities = Vec::new();
190
191 for i in 0..6 {
192 entities.push(Sprite::with_texture_and_rect(
193 entity_texture,
194 IntRect::new(96 * i, 0, 96, 96),
195 ));
196 }
197
198 let mut shader = Shader::from_file("edge.frag", ShaderType::Fragment)?;
199 shader.set_uniform_current_texture("texture")?;
200
201 Ok(Self {
202 surface,
203 bg_sprite,
204 entities,
205 shader,
206 })
207 }
208}
209
210impl Drawable for Edge<'_> {
211 fn draw<'a: 'shader, 'texture, 'shader, 'shader_texture>(
212 &'a self,
213 target: &mut dyn RenderTarget,
214 states: &RenderStates<'texture, 'shader, 'shader_texture>,
215 ) {
216 let mut states = *states;
217 states.shader = Some(&self.shader);
218 target.draw_with_renderstates(&Sprite::with_texture(self.surface.texture()), &states);
219 }
220}
221
222impl Effect for Edge<'_> {
223 fn update(&mut self, t: f32, x: f32, y: f32) -> SfResult<()> {
224 self.shader
225 .set_uniform_float("edge_threshold", 1. - (x + y) / 2.)?;
226 let entities_len = self.entities.len() as f32;
227
228 for (i, en) in self.entities.iter_mut().enumerate() {
229 let pos = (
230 (0.25 * (t * i as f32 + (entities_len - i as f32))).cos() * 300. + 350.,
231 (0.25 * (t * (entities_len - i as f32) + i as f32)).cos() * 200. + 250.,
232 );
233 en.set_position(pos);
234 }
235 self.surface.clear(Color::WHITE);
236 self.surface.draw(&self.bg_sprite);
237 for en in &self.entities {
238 self.surface.draw(en);
239 }
240 self.surface.display();
241 Ok(())
242 }
243 fn name(&self) -> &str {
244 "edge post-effect"
245 }
246}
247
248struct Geometry<'tex> {
249 point_cloud: [Vertex; 10_000],
250 shader: FBox<Shader<'tex>>,
251 texture: &'tex Texture,
252 transform: Transform,
253}
254
255impl<'tex> Geometry<'tex> {
256 fn new(texture: &'tex Texture) -> SfResult<Self> {
257 if !Shader::is_geometry_available() {
258 eprintln!("Geometry shaders not available");
259 return Err(SfError::CallFailed);
260 }
261 let mut shader = Shader::from_memory_all(
262 include_str!("resources/billboard.vert"),
263 include_str!("resources/billboard.geom"),
264 include_str!("resources/billboard.frag"),
265 )?;
266 shader.set_uniform_texture("texture", texture)?;
267 shader.set_uniform_vec2("resolution", (800., 600.).into())?;
268 let mut rng = SmallRng::seed_from_u64(1);
269 Ok(Self {
270 point_cloud: std::array::from_fn(|_| {
271 Vertex::new(
272 (
273 rng.random_range(-480.0..480.0),
274 rng.random_range(-480.0..480.0),
275 )
276 .into(),
277 Color::WHITE,
278 Default::default(),
279 )
280 }),
281 shader,
282 texture,
283 transform: Transform::IDENTITY,
284 })
285 }
286}
287
288impl Drawable for Geometry<'_> {
289 fn draw<'a: 'shader, 'texture, 'shader, 'shader_texture>(
290 &'a self,
291 target: &mut dyn RenderTarget,
292 states: &RenderStates<'texture, 'shader, 'shader_texture>,
293 ) {
294 let mut states = *states;
295 states.shader = Some(&self.shader);
296 states.texture = Some(self.texture);
297 states.transform = self.transform;
298 target.draw_primitives(&self.point_cloud, PrimitiveType::POINTS, &states);
299 }
300}
301
302impl Effect for Geometry<'_> {
303 fn update(&mut self, _t: f32, x: f32, y: f32) -> SfResult<()> {
304 self.transform = Transform::IDENTITY;
305 self.transform.translate(400., 300.);
306 self.transform.rotate(x * 360.0);
307 let size = 25. + y.abs() * 50.;
308 self.shader.set_uniform_vec2("size", size.into())?;
309 Ok(())
310 }
311
312 fn name(&self) -> &str {
313 "Geometry Shader Billboards"
314 }
315}
316
317fn main() -> SfResult<()> {
318 example_ensure_right_working_dir();
319
320 let mut window = RenderWindow::new(
321 (800, 600),
322 "SFML Shader",
323 Style::TITLEBAR | Style::CLOSE,
324 &Default::default(),
325 )?;
326 window.set_vertical_sync_enabled(true);
327 let font = Font::from_file("sansation.ttf")?;
328 let bg = Texture::from_file("background.jpg")?;
329 let mut bg_texture = Texture::from_file("sfml.png")?;
330 bg_texture.set_smooth(true);
331 let mut entity_texture = Texture::from_file("devices.png")?;
332 entity_texture.set_smooth(true);
333 let logo_texture = Texture::from_file("logo.png")?;
334 let effects: [&mut dyn Effect; 5] = [
335 &mut Pixelate::new(&bg)?,
336 &mut WaveBlur::new(&font)?,
337 &mut StormBlink::new()?,
338 &mut Edge::new(&bg_texture, &entity_texture)?,
339 &mut Geometry::new(&logo_texture)?,
340 ];
341 let mut current = 0;
342 let text_bg_texture = Texture::from_file("text-background.png")?;
343 let mut text_bg = Sprite::with_texture(&text_bg_texture);
344 text_bg.set_position((0., 520.));
345 text_bg.set_color(Color::rgba(255, 255, 255, 200));
346 let msg = format!("Current effect: {}", effects[current].name());
347 let mut desc = Text::new(&msg, &font, 20);
348 desc.set_position((10., 530.));
349 desc.set_fill_color(Color::rgb(80, 80, 80));
350 let msg = "Press left and right arrows to change the current shader";
351 let mut instructions = Text::new(msg, &font, 20);
352 instructions.set_position((280., 555.));
353 instructions.set_fill_color(Color::rgb(80, 80, 80));
354 let clock = Clock::start()?;
355
356 while window.is_open() {
357 while let Some(event) = window.poll_event() {
358 use crate::Event::*;
359 match event {
360 Closed => window.close(),
361 KeyPressed { code, .. } => match code {
362 Key::Escape => window.close(),
363 Key::Left => {
364 if current == 0 {
365 current = effects.len() - 1;
366 } else {
367 current -= 1;
368 }
369 desc.set_string(&format!("Current effect: {}", effects[current].name()));
370 }
371 Key::Right => {
372 if current == effects.len() - 1 {
373 current = 0;
374 } else {
375 current += 1;
376 }
377 desc.set_string(&format!("Current effect: {}", effects[current].name()));
378 }
379 _ => {}
380 },
381 _ => {}
382 }
383 }
384
385 let x = window.mouse_position().x as f32 / window.size().x as f32;
386 let y = window.mouse_position().y as f32 / window.size().y as f32;
387
388 effects[current].update(clock.elapsed_time().as_seconds(), x, y)?;
389
390 window.clear(Color::rgb(255, 128, 0));
391 window.draw(effects[current]);
392 window.draw(&text_bg);
393 window.draw(&instructions);
394 window.draw(&desc);
395 window.display();
396 }
397 Ok(())
398}
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?
184 fn new(bg_texture: &'t Texture, entity_texture: &'t Texture) -> SfResult<Self> {
185 let mut surface = RenderTexture::new(800, 600)?;
186 surface.set_smooth(true);
187 let mut bg_sprite = Sprite::with_texture(bg_texture);
188 bg_sprite.set_position((135., 100.));
189 let mut entities = Vec::new();
190
191 for i in 0..6 {
192 entities.push(Sprite::with_texture_and_rect(
193 entity_texture,
194 IntRect::new(96 * i, 0, 96, 96),
195 ));
196 }
197
198 let mut shader = Shader::from_file("edge.frag", ShaderType::Fragment)?;
199 shader.set_uniform_current_texture("texture")?;
200
201 Ok(Self {
202 surface,
203 bg_sprite,
204 entities,
205 shader,
206 })
207 }
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?
317fn main() -> SfResult<()> {
318 example_ensure_right_working_dir();
319
320 let mut window = RenderWindow::new(
321 (800, 600),
322 "SFML Shader",
323 Style::TITLEBAR | Style::CLOSE,
324 &Default::default(),
325 )?;
326 window.set_vertical_sync_enabled(true);
327 let font = Font::from_file("sansation.ttf")?;
328 let bg = Texture::from_file("background.jpg")?;
329 let mut bg_texture = Texture::from_file("sfml.png")?;
330 bg_texture.set_smooth(true);
331 let mut entity_texture = Texture::from_file("devices.png")?;
332 entity_texture.set_smooth(true);
333 let logo_texture = Texture::from_file("logo.png")?;
334 let effects: [&mut dyn Effect; 5] = [
335 &mut Pixelate::new(&bg)?,
336 &mut WaveBlur::new(&font)?,
337 &mut StormBlink::new()?,
338 &mut Edge::new(&bg_texture, &entity_texture)?,
339 &mut Geometry::new(&logo_texture)?,
340 ];
341 let mut current = 0;
342 let text_bg_texture = Texture::from_file("text-background.png")?;
343 let mut text_bg = Sprite::with_texture(&text_bg_texture);
344 text_bg.set_position((0., 520.));
345 text_bg.set_color(Color::rgba(255, 255, 255, 200));
346 let msg = format!("Current effect: {}", effects[current].name());
347 let mut desc = Text::new(&msg, &font, 20);
348 desc.set_position((10., 530.));
349 desc.set_fill_color(Color::rgb(80, 80, 80));
350 let msg = "Press left and right arrows to change the current shader";
351 let mut instructions = Text::new(msg, &font, 20);
352 instructions.set_position((280., 555.));
353 instructions.set_fill_color(Color::rgb(80, 80, 80));
354 let clock = Clock::start()?;
355
356 while window.is_open() {
357 while let Some(event) = window.poll_event() {
358 use crate::Event::*;
359 match event {
360 Closed => window.close(),
361 KeyPressed { code, .. } => match code {
362 Key::Escape => window.close(),
363 Key::Left => {
364 if current == 0 {
365 current = effects.len() - 1;
366 } else {
367 current -= 1;
368 }
369 desc.set_string(&format!("Current effect: {}", effects[current].name()));
370 }
371 Key::Right => {
372 if current == effects.len() - 1 {
373 current = 0;
374 } else {
375 current += 1;
376 }
377 desc.set_string(&format!("Current effect: {}", effects[current].name()));
378 }
379 _ => {}
380 },
381 _ => {}
382 }
383 }
384
385 let x = window.mouse_position().x as f32 / window.size().x as f32;
386 let y = window.mouse_position().y as f32 / window.size().y as f32;
387
388 effects[current].update(clock.elapsed_time().as_seconds(), x, y)?;
389
390 window.clear(Color::rgb(255, 128, 0));
391 window.draw(effects[current]);
392 window.draw(&text_bg);
393 window.draw(&instructions);
394 window.draw(&desc);
395 window.display();
396 }
397 Ok(())
398}
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