Home > front end >  Rust-SDL2: Is there a way to draw a singular pixel to screen?
Rust-SDL2: Is there a way to draw a singular pixel to screen?

Time:07-01

I'm making a project in Rust-SDL2, and I'm not exactly sure how to draw an individual pixel to the window. I tried looking into sdl2::rect::Point, but the documentation is rather confusing for me.

CodePudding user response:

It seems the documentation for the sdl2 crate is written for someone who already knows how sdl works and just wants to use it in Rust. You may want to run through a few tutorials first…
Then again, just string-searching for point led me to the right function.

Quick example with some flickering points:

use rand::Rng;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use sdl2::rect::Point;
use std::time::Duration;

pub fn main() {
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();

    let window = video_subsystem
        .window("rust-sdl2 demo", 800, 600)
        .position_centered()
        .build()
        .unwrap();

    let mut canvas = window.into_canvas().build().unwrap();

    let mut event_pump = sdl_context.event_pump().unwrap();
    let mut i = 0;
    let mut rng = rand::thread_rng();
    'running: loop {
        for event in event_pump.poll_iter() {
            match event {
                Event::Quit { .. }
                | Event::KeyDown {
                    ..
                } => break 'running,
                _ => {}
            }
        }
        canvas.set_draw_color(Color::RGB(0, 0, 0));
        canvas.clear();
        i = (i   1) % 255;
        canvas.set_draw_color(Color::RGB(i, 64, 255 - i));
        let (w, h) = canvas.output_size().unwrap();
        let mut points = [Point::new(0, 0); 256];
        points.fill_with(|| Point::new(rng.gen_range(0..w as i32), rng.gen_range(0..h as i32)));
        // For performance, it's probably better to draw a whole bunch of points at once
        canvas.draw_points(points.as_slice()).unwrap();

        canvas.present();
        ::std::thread::sleep(Duration::new(0, 1_000_000_000u32 / 60));
    }
}
  • Related