我有一个要构造的对象,需要其他对象:
[image] -> needed to construct -> [texture] -> needed to construct -> [sprite]
问题是我需要在纹理中交换图像以创建视觉效果。我有以下代码:
extern crate sfml;
use sfml::graphics::{Color, Image, RenderTarget, RenderWindow, Sprite, Texture};
use sfml::window::{Event, Key, Style};
const WIDTH: u32 = 1024;
const HEIGHT: u32 = 768;
fn main() {
let mut window = RenderWindow::new(
(WIDTH, HEIGHT),
"Custom drawable",
Style::CLOSE,
&Default::default(),
);
let mut image = Image::from_color(WIDTH, HEIGHT, &Color::BLUE).unwrap();
let mut texture = Texture::from_image(&image).unwrap();
let sprite_canvas = Sprite::with_texture(&texture);
let mut x: u32 = 0;
loop {
while let Some(event) = window.poll_event() {
match event {
Event::Closed
| Event::KeyPressed {
code: Key::Escape, ..
} => return,
_ => {}
}
}
x += 1;
image.set_pixel(x, x, &Color::YELLOW);
texture.update_from_image(&image, 0, 0);
window.draw(&sprite_canvas);
window.display()
}
}
这是“货运”示例时出现的错误
error[E0502]: cannot borrow `texture` as mutable because it is also borrowed as immutable
--> src/main.rs:35:9
|
19 | let sprite_canvas = Sprite::with_texture(&texture);
| ------- immutable borrow occurs here
...
35 | texture.update_from_image(&image, 0, 0);
| ^^^^^^^ mutable borrow occurs here
...
39 | }
| - immutable borrow ends here
出于性能方面的考虑,应避免复制或克隆纹理或图像;克隆大图像可能会导致性能下降。
我使它与这段代码一起工作,但是不确定是否是最好的解决方案,因为我正在每帧中重新创建纹理。
extern crate sfml;
use sfml::graphics::{Color, RenderTarget, RenderWindow, Sprite, Texture, Image, Transformable, Text, Font};
use sfml::window::{Event, Key, Style};
const WIDTH: u32 = 1024;
const HEIGHT: u32 = 768;
fn main() {
let mut window = RenderWindow::new(
(WIDTH, HEIGHT),
"Custom drawable",
Style::CLOSE,
&Default::default(),
);
window.set_vertical_sync_enabled(true);
let mut image_canvas = Image::from_color(WIDTH, HEIGHT, &Color::BLACK).unwrap();
let mut x: f32 = 0.0;
let mut y: f32 = 0.0;
let mut image_swap = false;
loop {
while let Some(event) = window.poll_event() {
match event {
Event::Closed
| Event::KeyPressed {
code: Key::Escape, ..
} => return,
_ => {}
}
}
if Key::Left.is_pressed() {
x -= 1.0;
}
if Key::Right.is_pressed() {
x += 1.0;
}
if Key::Up.is_pressed() {
y -= 1.0;
}
if Key::Down.is_pressed() {
y += 1.0;
}
image_canvas.set_pixel(x as u32, y as u32, &Color::YELLOW);
let texture_3 = Texture::from_image(&image_canvas).unwrap();
let sprite_canvas = Sprite::with_texture(&texture_3);
image_swap = !image_swap;
window.clear(&Color::BLACK);
window.draw(&sprite_canvas);
window.display()
}
}