#[non_exhaustive]
pub struct PixState { /* private fields */ }
Expand description

Represents all state and methods for updating and interacting with the PixEngine.

Implementations

Clears the render target to the current background Color set by PixState::background.

Errors

If the current render target is closed or dropped, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.background(Color::CADET_BLUE);
    s.clear();
    Ok(())
}

Save a portion src of the currently rendered target to a png file. Passing None for src saves the entire target.

Errors

Returns an error for any of the following: - The current render target is closed or dropped. - The renderer fails to read pixels from the current window target. - An io::Error occurs attempting to create the png file. - A png::EncodingError occurs attempting to write image bytes.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    if let Key::S = event.key {
        s.save_canvas(None, "test_image.png")?;
    }
    Ok(false)
}

Draw a Point to the current canvas. PixState::stroke controls whether the point is drawn or not. PixState::stroke_weight and PixState::fill have no effect.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.stroke(Color::RED);
    s.point(s.mouse_pos())?;
    Ok(())
}

Draw a Line to the current canvas. PixState::stroke controls whether the line is drawn or not. PixState::stroke_weight controls the line thickness. PixState::fill has no effect.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.stroke(Color::RED);
    s.line([s.pmouse_pos(), s.mouse_pos()])?;
    Ok(())
}

Draw a cubic Bezier curve to the current canvas. PixState::stroke controls whether the line is drawn or not. PixState::bezier_detail controls the resolution of the curve. PixState::fill has no effect.

The first and last points are the anchor points of the curve, while the middle points are the control points that “pull” the curve towards them.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.stroke(Color::RED);
    s.bezier([[85, 20], [10, 10], [90, 90], [15, 80]])?;
    Ok(())
}

Draw a Triangle to the current canvas. PixState::fill and PixState::stroke control whether the triangle is filled or outlined.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLACK);
    s.stroke(Color::RED);
    s.triangle(tri!([10, 0], [-5, 5], [5, 5]))?;
    Ok(())
}

Draw a square Rect to the current canvas. PixState::fill and PixState::stroke control whether the square is filled or outlined. RectMode controls how the (x, y) position is interpreted.

Alias for PixState::rect.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLACK);
    s.stroke(Color::RED);
    s.square(square![s.mouse_pos(), 100])?;
    Ok(())
}

Draw a rounded Square to the current canvas. PixState::fill and PixState::stroke control whether the square is filled or outlined. RectMode controls how the (x, y) position is interpreted.

Alias for PixState::rounded_rect.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLACK);
    s.stroke(Color::RED);
    s.rounded_square(square![s.mouse_pos(), 100], 10)?;
    Ok(())
}

Draw a Rectangle to the current canvas. PixState::fill and PixState::stroke control whether the rect is filled or outlined. RectMode controls how the (x, y) position is interpreted.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLACK);
    s.stroke(Color::RED);
    s.rect(rect![s.mouse_pos(), 100, 100])?;
    Ok(())
}

Draw a rounded Rectangle to the current canvas. PixState::fill and PixState::stroke control whether the rect is filled or outlined. RectMode controls how the (x, y) position is interpreted.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLACK);
    s.stroke(Color::RED);
    s.rounded_rect(rect![s.mouse_pos(), 100, 100], 10)?;
    Ok(())
}

Draw a Quadrilateral to the current canvas. PixState::fill and PixState::stroke control whether the quad is filled or outlined. RectMode has no effect.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLACK);
    s.stroke(Color::RED);
    s.quad(quad![10, 20, 30, 10, 20, 25, 15, 15])?;
    Ok(())
}

Draw a polygon to the current canvas. PixState::fill and PixState::stroke control whether the polygon is filled or outlined. RectMode has no effect.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLACK);
    s.stroke(Color::RED);
    s.polygon([[10, 10], [50, 20], [70, 30], [60, 50], [10, 50]])?;
    Ok(())
}

Draw a wireframe to the current canvas, translated to a given Point and optionally rotated by angle and scaled. PixState::fill and PixState::stroke control whether the wireframe is filled or outlined. angle can be in either radians or degrees based on AngleMode.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    let wireframe = [
        point!(5.0, 0.0),
        point!(-2.5, -2.5),
        point!(-2.5, 2.5)
    ];
    s.fill(Color::CADET_BLUE);
    s.stroke(Color::BLACK);
    s.angle_mode(AngleMode::Degrees);
    s.wireframe(wireframe, [10, 10], 45.0, 2.0)?;
    Ok(())
}

Draw a circle Ellipse to the current canvas. PixState::fill and PixState::stroke control whether the circle is filled or outlined. EllipseMode controls how the (x, y) position is interpreted.

Alias for PixState::ellipse.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLACK);
    s.stroke(Color::RED);
    s.circle(circle![s.mouse_pos(), 100])?;
    Ok(())
}

Draw a Ellipse to the current canvas. PixState::fill and PixState::stroke control whether the ellipse is filled or outlined. EllipseMode controls how the (x, y) position is interpreted.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLACK);
    s.stroke(Color::RED);
    s.ellipse(ellipse![s.mouse_pos(), 100, 100])?;
    Ok(())
}

Draw an arc of a given radius and length defined by start and end to the current canvas. PixState::fill and PixState::stroke control whether the pie is filled or outlined. ArcMode changes whether the arc is drawn as an open segment or a pie shape.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLACK);
    s.stroke(Color::RED);
    s.arc_mode(ArcMode::Pie);
    s.arc(s.mouse_pos(), 20, 0, 180)?;
    Ok(())
}

Add samples to the current audio buffer queue.

Errors

If the audio device fails to queue samples, or if the audio buffer max size is reached, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    // Some square wave samples of audio
    let volume = 0.2;
    let sample_rate = s.audio_sample_rate() as f32;
    let sample_count = 4 * sample_rate as usize;
    let frequency = 440.0; // A4 note
    let mut samples = Vec::with_capacity(sample_count);
    for x in 0..sample_count {
        let s = (2.0 * PI as f32 * frequency * x as f32 / sample_rate).sin();
        samples.push(if s <= 0.0 { -volume } else { volume });
    }
    // Add samples to audio queue for playback
    s.enqueue_audio(&samples)?;
    Ok(())
}

Clear audio samples from the current audio buffer queue.

Return the status of the current audio queue device.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    match event.key {
        Key::Return => {
            if s.audio_status() == AudioStatus::Paused {
                s.resume_audio();
            }
            Ok(true)
        }
        _ => Ok(false),
    }
}

Return the current driver of this audio callback device.

Returns the sample rate for the current audio queue device.

Returns the queued buffer size of the current audio queue device.

Returns the buffer size of the current audio queue device.

Resumes playback of the current audio queue device.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    match event.key {
        Key::Return => {
            s.resume_audio();
            Ok(true)
        }
        _ => Ok(false),
    }
}

Pause playback of the current audio queue device.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    match event.key {
        Key::Return => {
            s.pause_audio();
            Ok(true)
        }
        _ => Ok(false),
    }
}

Opens and returns an audio callback device for playback.

The audio device starts out paused. Call resume to start playback and pause to stop playback.

Errors

If the renderer fails to open an audio device, then an error is returned.

Example
use pix_engine::prelude::*;
use std::time::Duration;

struct SquareWave {
    phase_inc: f32,
    phase: f32,
    volume: f32,
}

impl AudioCallback for SquareWave {
    type Channel = f32;

    fn callback(&mut self, out: &mut [Self::Channel]) {
        // Generate a square wave
        for x in out.iter_mut() {
            *x = if self.phase <= 0.5 {
                self.volume
            } else {
                -self.volume
            };
            self.phase = (self.phase + self.phase_inc) % 1.0;
        }
    }
}

struct MyApp;

impl AppState for MyApp {
    fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
        let desired_spec = AudioSpecDesired {
            freq: Some(44_100), // 44,100 HZ
            channels: Some(1),  // mono audio
            samples: None,      // default sample size
        };
        let mut device = s.open_playback(None, &desired_spec, |spec| {
            SquareWave {
                phase_inc: 440.0 / spec.freq as f32,
                phase: 0.0,
                volume: 0.25,
            }
        })?;

        // Start playback
        device.resume();

        // Play for 2 seconds then quit.
        std::thread::sleep(Duration::from_millis(2000));
        s.quit();

        // Device stops playback when dropped.
        Ok(())
    }
}

Opens and returns an audio capture device for recording.

The audio device starts out paused. Call resume to start recording and pause to stop recording.

Errors

If the renderer fails to open an audio device, then an error is returned.

Example
use pix_engine::prelude::*;
use std::{sync::mpsc, time::Duration};

struct Recording {
    record_buffer: Vec<f32>,
    pos: usize,
    tx: mpsc::Sender<Vec<f32>>,
    done: bool,
}

impl AudioCallback for Recording {
    type Channel = f32;

    fn callback(&mut self, input: &mut [Self::Channel]) {
        if self.done {
            return;
        }
        for x in input {
           self.record_buffer[self.pos] = *x;
           self.pos += 1;
           if self.pos >= self.record_buffer.len() {
               self.done = true;
               self.tx
                   .send(self.record_buffer.clone())
                   .expect("could not send record buffer");
               break;
           }
        }
    }
}

struct MyApp;

const RECORDING_LENGTH_SECONDS: usize = 3;

impl AppState for MyApp {
    fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
        let desired_spec = AudioSpecDesired {
            freq: None,     // default device frequency
            channels: None, // default device channels
            samples: None,  // default sample size
        };

        let (tx, rx) = mpsc::channel();
        let capture_device = s.open_capture(None, &desired_spec, |spec| {
            Recording {
                record_buffer: vec![
                    0.0;
                    spec.freq as usize
                        * RECORDING_LENGTH_SECONDS
                        * spec.channels as usize
                ],
                pos: 0,
                tx,
                done: false,
            }
        })?;

        // Start playback
        capture_device.resume();

        // Wait for recording to finish
        let recorded_samples = rx.recv()?;
        capture_device.pause();

        // Handle recorded_samples

        // Device stops playback when dropped.
        Ok(())
    }
}

Draw an Image to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    let image = Image::from_file("./some_image.png")?;
    s.image(&image, [10, 10])?;
    Ok(())
}

Draw a transformed Image to the current canvas resized to the target rect, optionally rotated by an angle about the center point or flipped. angle can be in either radians or degrees based on AngleMode. PixState::image_tint can optionally add a tint color to the rendered image.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.angle_mode(AngleMode::Degrees);
    let image = Image::from_file("./some_image.png")?;
    let src = None; // Draw entire image instead of a sub-image
    let dst = image.bounding_rect_offset([10, 10]); // Draw image at `(10, 10)`.
    let angle = 10.0;
    let center = point!(10, 10);
    s.image_transformed(&image, src, dst, angle, center, Flipped::Horizontal)?;
    Ok(())
}

Present all renderer changes since last frame.

Returns whether any active window has focus. To check focus of a specific window, see PixState::focused_window.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.focused() {
        // Update screen only when focused
        s.rect([0, 0, 100, 100])?;
    }
    Ok(())
}

Returns whether a given window has focus. To check focus of a any window, see PixState::focused.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.focused_window(s.window_id()) {
        // Update screen only when focused
        s.rect([0, 0, 100, 100])?;
    }
    Ok(())
}

The Duration elapsed since last frame.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    // Update position based on frame timestep
    self.position = self.velocity * s.delta_time().as_secs_f64();
    Ok(())
}

The [Duration[ elapsed since application start.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    // Draw a blinking box, indepdendent of frame rate
    if s.elapsed().as_millis() >> 9 & 1 > 0 {
        s.rect([0, 0, 10, 10])?;
    }
    Ok(())
}

The total number of frames rendered since application start.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    // Create a strobe effect, dependent on frame rate
    if s.frame_count() % 5 == 0 {
        s.rect([0, 0, 10, 10])?;
    }
    Ok(())
}

Run the render loop 1 time by calling AppState::on_update.

This can be used to only redraw in response to user actions such as AppState::on_mouse_pressed or AppState::on_key_pressed.

Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
    s.run(false); // Disable render loop
    Ok(())
}
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    // Step one frame draw at a time on each space press
    // Useful for debugging frame-by-frame
    if let Key::Space = event.key {
        s.redraw();
        return Ok(true);
    }
    Ok(false)

Run the render loop N times by calling AppState::on_update.

This can be used to only redraw in response to user actions such as AppState::on_mouse_pressed or AppState::on_key_pressed.

Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
    s.run(false); // Disable render loop
    Ok(())
}
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    // Step one frame draw at a time on each space press
    // Useful for debugging by multiple frames at a time
    if let Key::Space = event.key {
        s.run_times(4);
        return Ok(true);
    }
    Ok(false)

The average frames per second rendered.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text(format!("FPS: {}", s.avg_frame_rate()))?;
    Ok(())

Trigger application quit.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.button("Quit?")? {
        s.quit();
    }
    Ok(())

Abort application quit and resume render loop by calling AppState::on_update.

Example
fn on_stop(&mut self, s: &mut PixState) -> PixResult<()> {
    if self.has_unsaved_changes {
        self.prompt_save_dialog = true;
        s.abort_quit();
    }
    Ok(())

Return the current day between 1-31.

Return the current month between 1-12.

Return the current year as an integer.

Return the current hour between 0-23.

Return the current minute between 0-59.

Return the current second between 0-59.

Sets the Color value used to clear the canvas.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.background(Color::ALICE_BLUE);
    s.clear();
    Ok(())
}

Sets the Color value used to fill shapes drawn on the canvas. None disables fill entirely.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::ALICE_BLUE);
    s.rect([0, 0, 100, 100])?;
    s.fill((None));
    s.rect([25, 25, 75, 75])?;
    Ok(())
}

Sets the Color value used to outline shapes drawn on the canvas. None disables stroke entirely.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.stroke(Color::BLACK);
    s.rect([0, 0, 100, 100])?;
    s.stroke((None));
    s.rect([25, 25, 75, 75])?;
    Ok(())
}

Sets the width used to draw lines on the canvas.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.stroke(Color::BLUE);
    s.stroke_weight(2);
    // Draws a 2-pixel wide diagonal line
    s.line(line_![0, 0, 100, 100])?;
    Ok(())
}

Set the font size for drawing to the current canvas.

Errors

If the renderer fails to load the given font size from the currently loaded font data, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.font_size(22);
    s.text("Some big text")?;
    Ok(())
}

Set the font style for drawing to the current canvas.

Errors

If the renderer fails to load the current font, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.font_style(FontStyle::BOLD);
    s.text("Some bold text")?;
    Ok(())
}

Set the font family for drawing to the current canvas.

Errors

If the renderer fails to load the given font size from the currently loaded font data, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.font_family(Font::NOTO)?;
    s.text("Some NOTO family text")?;
    s.font_family(Font::from_file("Custom font", "./custom_font.ttf"))?;
    s.text("Some custom family text")?;
    Ok(())
}

Sets the text shadow distance used to draw text on the canvas.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text_shadow(2);
    // Draws a 2-pixel offset shhadow
    s.text("Shadowed")?;
    Ok(())
}

Enable or disable the anti-alias option used for drawing shapes on the canvas. smooth is enabled by default.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    // Draws a anti-aliased diagonal line
    s.smooth(true);
    s.line(line_![0, 0, 100, 100])?;
    // Disables anti-aliasing
    s.smooth(false);
    s.line(line_![0, 0, 100, 100])?;
    Ok(())
}

Set the resolution at which PixState::bezier curves are displayed. The default is 20.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.bezier_detail(5);
    s.stroke(Color::RED);
    s.bezier([[85, 20], [10, 10], [90, 90], [15, 80]])?;
    Ok(())
}

Sets the wrap width used to draw text on the canvas. None disables text wrap.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    // Renders as (depending on font width):
    //
    // Lorem ipsum
    // dollor sit amet,
    // consetetur
    // sadipscing
    // elitr, sed diam
    s.wrap(100);
    s.text("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam")?;

    // Disable wrapping
    s.wrap((None));
    s.text("Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam")?;
    Ok(())
}

Sets the clip Rect used by the renderer to draw to the current canvas. None disables clipping.

Errors

If the current render target is closed or dropped, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.clip(rect![0, 0, 100, 100])?;
    // Renders a quarter pie-slice with radius 100
    s.circle([100, 100, 200, 200])?;
    Ok(())
}

Set the application to fullscreen or not.

Errors

If the current render target is closed or dropped or the renderer fails to set fullscreen, then an error is returned.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    if let Key::Return = event.key {
        s.fullscreen(true)?;
        return Ok(true);
    }
    Ok(false)
}

Toggle fullscreen.

Errors

If the current render target is closed or dropped or the renderer fails to toggle fullscreen, then an error is returned.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    if let Key::Return = event.key {
        s.toggle_fullscreen()?;
        return Ok(true);
    }
    Ok(false)
}

Set the window to synchronize frame rate to the screens refresh rate (VSync).

Note

Due to the current limitation with changing VSync at runtime, this method creates a new window using the properties of the current window and returns the new WindowId.

If you are storing and interacting with this window using the WindowId, make sure to use the newly returned WindowId.

Errors

If the current render target is closed or dropped or the renderer fails to set vsync, then an error is returned.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    if let Key::Return = event.key {
        s.vsync(true)?;
        return Ok(true);
    }
    Ok(false)
}

Toggle synchronizing frame rate to the screens refresh rate (VSync).

Note

Due to the current limitation with changing VSync at runtime, this method creates a new window using the properties of the current window and returns the new WindowId.

If you are storing and interacting with this window using the WindowId, make sure to use the newly returned WindowId.

Errors

If the current render target is closed or dropped or the renderer fails to toggle vsync, then an error is returned.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    if let Key::Return = event.key {
        s.toggle_vsync()?;
        return Ok(true);
    }
    Ok(false)
}

Set the mouse cursor to a predefined symbol or image. None hides the cursor.

Errors

If the renderer fails to set the cursor or load it from an image file, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text("Hover me")?;
    if s.hovered() {
        s.cursor(Cursor::hand())?;
    } else {
        s.cursor(Cursor::arrow())?;
    }
    Ok(())
}

Disables any UI elements drawn after this is called, preventing them from being interacted with.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.button("Disable UI")? {
        s.disable(true);
    }
    s.checkbox("Disabled checkbox", &mut self.checkbox)?;
    Ok(())
}

Whether the render loop is running or not.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    if let Key::Return = event.key {
        // Toggle pausing rendering
        let running = s.running();
        s.run(!running);
        return Ok(true);
    }
    Ok(false)
}

Pause or resume the render loop called by AppState::on_update.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    if let Key::Return = event.key {
        // Toggle rendering
        let running = s.running();
        s.run(running);
        return Ok(true);
    }
    Ok(false)
}

Set whether to show the current frame rate per second in the title or not.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    if let Key::Return = event.key {
        s.show_frame_rate(true);
        return Ok(true);
    }
    Ok(false)
}

Get the target frame rate to render at.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    if let Key::Down = event.key {
        let target = s.target_frame_rate().unwrap_or(60);
        s.frame_rate(target - 10);
        return Ok(true);
    }
    Ok(false)
}

Set a target frame rate to render at, controls how often AppState::on_update is called. None clears the target frame rate.

Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
    // Target a lower FPS than natively possible
    s.frame_rate(30);
    Ok(())
}

Set the rendering scale of the current canvas. Drawing coordinates are scaled by x/y factors before being drawn to the canvas.

Errors

If the current render target is closed or dropped, or (x, y) contain invalid values, then an error is returned.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    if let Key::Plus = event.key {
        s.scale(2.0, 2.0)?;
        return Ok(true);
    }
    Ok(false)
}

Change the way parameters are interpreted for drawing Squares and Rectangles.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.rect_mode(RectMode::Center);
    // Draw rect with center at `(100, 100)`
    s.rect([100, 100, 50, 50])?;
    Ok(())
}

Change the way parameters are interpreted for drawing Ellipses.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.ellipse_mode(EllipseMode::Center);
    // Draw ellipse with center at `(100, 100)`
    s.ellipse([100, 100, 50, 50])?;
    Ok(())
}

Change the way parameters are interpreted for drawing Images.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.image_mode(ImageMode::Center);
    // Draw image with center at `(100, 100)`
    s.image(&Image::from_file("./some_image.png")?, [100, 100])?;
    Ok(())
}

Add a color tint to Images when drawing.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.image_tint(Color::RED);
    // Draw image tinted red
    s.image(&Image::from_file("./some_image.png")?, [0, 0])?;
    Ok(())
}

Change the way arcs are drawn.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    // Draw arc as a open, unfilled pie segment using only the `stroke` (The default)
    s.arc_mode(ArcMode::Default);
    s.arc([100, 100], 20, 0, 180)?;
    s.arc_mode(ArcMode::Pie);
    // Draw arc as a closed pie segment using both `fill` and `stroke`
    s.arc([200, 200], 20, 0, 180)?;
    Ok(())
}

Change the way angles are interpreted for rotation and matrix transformations.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.angle_mode(AngleMode::Degrees);
    let angle = 10.0;
    let center = point!(10, 10);
    s.text_transformed("Rotated text", angle, center, None)?;
    Ok(())
}

Change the way textures are blended together.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.blend_mode(BlendMode::Blend);
    // Draw image with alpha blended with background
    s.image(&Image::from_file("./some_image.png")?, [0, 0])?;
    Ok(())
}

Saves the current draw settings and transforms.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLUE);
    s.stroke(Color::WHITE);

    s.push(); // Save settings

    s.fill(Color::RED);
    s.stroke(Color::BLACK);
    s.rect([0, 0, 100, 100])?;

    s.pop(); // Restore settings

    // Rectangle is blue with a white outline
    s.rect([0, 0, 100, 100])?;
    Ok(())
}

Restores the previous draw settings and transforms, if present. If the settings stack is empty, the settings will remain unchanged.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.fill(Color::BLUE);
    s.stroke(Color::WHITE);

    s.push(); // Save settings

    s.fill(Color::RED);
    s.stroke(Color::BLACK);
    s.rect([0, 0, 100, 100])?;

    s.pop(); // Restore settings

    // Rectangle is blue with a white outline
    s.rect([0, 0, 100, 100])?;
    Ok(())
}

Get the current window title.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text(format!("Window title: {}", s.title()))?;
    Ok(())
}

Set the current window title.

Errors

If the current window target is closed or invalid or the string contains a nul byte, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.button("Change title")? {
        s.set_title("Title changed!")?;
    }
    Ok(())
}

Returns the current mouse position coordinates this frame as (x, y).

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    // Draw 100x100 rectangle that follows the mouse
    s.rect(rect![s.mouse_pos(), 100, 100])?;
    Ok(())
}

Returns the previous mouse position coordinates last frame as (x, y).

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    // Draw 100x100 rectangle that follows the mouse last frame
    // Creates a yoyo-like effect
    s.rect(rect![s.pmouse_pos(), 100, 100])?;
    Ok(())
}

Returns if any Mouse button was pressed this frame.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.mouse_pressed() {
        s.background(Color::random());
    }
    Ok(())
}

Returns if the Mouse was clicked (pressed and released) this frame.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.mouse_clicked(Mouse::Left) {
        s.background(Color::random());
    }
    Ok(())
}

Returns if the Mouse was double clicked (pressed and released) this frame.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.mouse_dbl_clicked(Mouse::Left) {
        s.background(Color::random());
    }
    Ok(())
}

Returns if a specific Mouse button was pressed this frame.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.mouse_down(Mouse::Left) {
        s.background(Color::random());
    }
    Ok(())
}

Returns a list of the current mouse buttons pressed this frame.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    // Only trigger if both buttons are pressed
    if s.mouse_buttons().contains(&Mouse::Left)
       && s.mouse_buttons().contains(&Mouse::Right)
    {
        s.background(Color::random());
    }
    Ok(())
}

Returns if any Key was pressed this frame.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.key_pressed() {
        s.background(Color::random());
    }
    Ok(())
}

Returns if a specific Key was pressed this frame.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.key_down(Key::Space) {
        s.background(Color::random());
    }
    Ok(())
}

Returns a list of the current keys pressed this frame.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.keys().contains(&Key::Space) && s.keys().contains(&Key::Up) {
        s.background(Color::random());
    }
    Ok(())
}

Returns if a specific KeyMod was pressed this frame.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.keymod_down(KeyMod::CTRL) && s.key_down(Key::Space) {
        s.background(Color::random());
    }
    Ok(())
}

Returns a list of the current key modifiers pressed this frame.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.keymod().intersects(KeyMod::SHIFT | KeyMod::CTRL)
        && s.key_down(Key::Space)
    {
        s.background(Color::random());
    }
    Ok(())
}

Polls for events from the underlying renderer.

Open a controller with a given ID to start handling events.

Errors

If the ControllerId is invalid or the renderer fails to open the controller, then an error is returned.

Close a controller with a given ID to stop handling events.

Draw a portion src of a texture to the current render target translated and resized to the target dst. Passing None for src renders the entire texture. Passing None for dst renders to the maximum size of the render target.

Note

It’s possible to render one texture onto another texture, but currently they both have to have been created in the same window. Attempting to render to a texture created with another window will result in a PixError::InvalidTexture. This restriction may be lifted in the future.

Errors

Returns an error for any of the following: - The current render target is closed or dropped. - The texture being rendered has been dropped. - The target texture is the same as the texture being rendered. - The renderer fails to draw to the texture.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.with_texture(self.texture_id, |s: &mut PixState| -> PixResult<()> {
        s.background(Color::random());
        s.text("Rendered texture!")?;
        Ok(())
    })?;
    let src = rect![10, 10, 100, 100]; // Render a sub-section of the texture
    // translate and scale texture
    let dst = rect![200, 200, 200, 200];
    s.texture(self.texture_id, src, dst)?;
    Ok(())
}

Draw a transformed portion src of a texture to the current render target translated and resized to the target dst, optionally rotated by an angle about a center point or flipped. angle can be in either radians or degrees based on AngleMode. Passing None for src renders the entire texture. Passing None for dst renders to the maximum size of the render target. PixState::image_tint can optionally add a tint color to the rendered texture.

Note

It’s possible to render one texture onto another texture, but currently they both have to have been created in the same window. Attempting to render to a texture created with another window will result in a PixError::InvalidTexture. This restriction may be lifted in the future.

Errors

Returns an error for any of the following: - The current render target is closed or dropped. - The texture being rendered has been dropped. - The target texture is the same as the texture being rendered. - The renderer fails to draw to the texture.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.with_texture(self.texture_id, |s: &mut PixState| -> PixResult<()> {
        s.background(Color::random());
        s.text("Rendered texture!")?;
        Ok(())
    })?;
    let src = None;
    // translate and scale texture
    let dst = rect![200, 200, 200, 200];
    let angle = 10.0;
    let center = point!(10, 10);
    s.texture_transformed(
        self.texture_id,
        src,
        dst,
        angle,
        center,
        Flipped::Horizontal,
    )?;
    Ok(())
}

Constructs a Texture to render to. Passing None for PixelFormat will use PixelFormat::default.

Errors

If the current window target is closed or invalid, or the texture dimensions are invalid, then an error is returned.

Note

Textures are automatically dropped when the window they were created in is closed due to an implicit lifetime that the texture can not outlive the window it was created for. Calling this method will associate the texture to the current window_target, which can only be changed using the PixState::with_window method. It is the responsibility of the caller to manage created textures and call PixState::delete_texture when a texture resource is no longer needed and to ensure that texture methods are not called for a given window after it has been closed, otherwise an error will be returned.

This constraint arises due to lifetime issues with SDL textures, See https://github.com/Rust-SDL2/rust-sdl2/issues/1107 for more details.

Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
    self.texture_id = s.create_texture(
        s.width()? / 2,
        s.height()? / 2,
        PixelFormat::Rgb,
    )?;
    Ok(())
}

Delete a Texture.

Errors

If the current window target is closed or invalid, or the texture has already been dropped, then an error is returned.

Note

Currently, it is up to the caller to manage valid textures. Textures become invalid whenever the window_target they were created in has been closed. Calling any texture methods with an invalid TextureId will result in an error.

This constraint arises due to lifetime issues with SDL textures, See https://github.com/Rust-SDL2/rust-sdl2/issues/1107 for more details.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    // A more polished implementation would manage state in `self` to avoid re-creating and
    // destroying textures every frame
    let texture_id = s.create_texture(500, 600, PixelFormat::Rgb)?;
    // Render things
    s.delete_texture(texture_id)?;
    Ok(())
}

Update the Texture with a u8 slice of pixel data. Passing None for rect updates the entire texture. pitch is the number of bytes in a row of pixels data including padding between lines.

Errors

If the window in which the texture was created is closed, or the renderer fails to update to the texture, then an error is returned.

Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
    self.texture_id = s.create_texture(500, 600, None)?;
    let image = Image::from_file("./some_image.png")?;
    s.update_texture(self.texture_id, None, image.as_bytes(), image.pitch())?;
    Ok(())
}

Target a Texture for drawing operations.

Errors

If the window in which the texture was created is closed, or the renderer fails to update to the texture, then an error is returned.

Example
fn on_start(&mut self, s: &mut PixState) -> PixResult<()> {
    self.texture_id = s.create_texture(500, 600, None)?;
    s.with_texture(self.texture_id, |s: &mut PixState| -> PixResult<()> {
        s.background(Color::random());
        s.text("Rendered texture!")?;
        Ok(())
    })?;
    Ok(())
}

Save a portion src of a texture to a png file. Passing None for src saves the entire texture.

Errors

Returns an error for any of the following: - The window in which the texture was created is closed. - The renderer fails to read pixels from the texture. - An io::Error occurs attempting to create the png file. - A png::EncodingError occurs attempting to write image bytes.

Example
fn on_key_pressed(&mut self, s: &mut PixState, event: KeyEvent) -> PixResult<bool> {
    if let Key::S = event.key {
        let texture_id = s.create_texture(200, 200, None)?;
        s.with_texture(texture_id, |s: &mut PixState| -> PixResult<()> {
            s.background(Color::random());
            s.text("Rendered texture!")?;
            Ok(())
        })?;
        s.save_texture(texture_id, None, "test_image.png")?;
    }
    Ok(false)
}

Get the current window target ID.

Create a new WindowBuilder.

Close a window.

Errors

If the window has already been closed or is invalid, then an error is returned.

The dimensions of the current render target as (width, height).

Errors

If the window has been closed or is invalid, then an error is returned.

The dimensions of the current window as (width, height).

Errors

If the window has been closed or is invalid, then an error is returned.

Set the dimensions of the current window from (width, height).

Errors

If the window has been closed or is invalid, then an error is returned.

Returns the rendering viewport of the current render target.

Errors

If the window has been closed or is invalid, then an error is returned.

Set the rendering viewport of the current render target.

Errors

If the window has been closed or is invalid, then an error is returned.

Clears the rendering viewport of the current render target back to the entire target.

Errors

If the window has been closed or is invalid, then an error is returned.

The width of the current render target.

Errors

If the window has been closed or is invalid, then an error is returned.

The width of the current window.

Errors

If the window has been closed or is invalid, then an error is returned.

Set the width of the current window.

Errors

If the window has been closed or is invalid, then an error is returned.

The height of the current render target.

Errors

If the window has been closed or is invalid, then an error is returned.

The height of the current window.

Errors

If the window has been closed or is invalid, then an error is returned.

Set the height of the current window.

Errors

If the window has been closed or is invalid, then an error is returned.

The center Point of the current render target.

Errors

If the window has been closed or is invalid, then an error is returned.

The center Point of the current window.

Errors

If the window has been closed or is invalid, then an error is returned.

The dimensions of the primary display as (width, height).

Errors

If the window has been closed or is invalid, then an error is returned.

The width of the primary display.

Errors

If the window has been closed or is invalid, then an error is returned.

The height of the primary display.

Errors

If the window has been closed or is invalid, then an error is returned.

Show the current window target.

Errors

If the window has been closed or is invalid, then an error is returned.

Hide the current window target.

Errors

If the window has been closed or is invalid, then an error is returned.

Target a Window for drawing operations.

Errors

If the window has been closed or is invalid, or the rendering function fails, then an error is returned.

Reset current UI rendering position back to the previous line with item padding, and continue with horizontal layout.

You can optionally change the item padding, or set a different horizontal or vertical position by passing in an offset.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text("Text")?;
    s.same_line(None);
    s.text("Same line")?;
    Ok(())
}

Change the default width of the next rendered element for elements that typically take up the remaining width of the window/frame they are rendered in.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.next_width(200);
    if s.button("Button")? {
        // was clicked
    }
    Ok(())
}

Draw a tabbed view to the current canvas. It accepts a list of tabs to be rendered, which one is selected and a closure that is passed the current tab and &mut PixState which you can use to draw all the standard drawing primitives and change any drawing settings. Settings changed inside the closure will not persist, similar to PixState::with_texture. Returns true if a tab selection was changed.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.tab_bar(
        "Tab bar",
        &["Tab 1", "Tab 2"],
        &mut self.selected,
        |tab: &&str, s: &mut PixState| {
            match tab {
                &"Tab 1" => {
                    s.text("Tab 1")?;
                    s.separator();
                    s.text("Some Content")?;
                }
                &"Tab 2" => {
                    s.next_width(200);
                    if s.button("Click me")? {
                        // was clicked
                    }
                }
                _ => (),
            }
            Ok(())
        }
    )?;
    Ok(())
}

Draw a newline worth of spacing to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text("Some text")?;
    s.spacing()?;
    s.text("Some other text")?;
    Ok(())
}

Draw an indent worth of spacing to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.indent()?;
    s.text("Indented!")?;
    Ok(())
}

Draw a horizontal or vertical separator to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text("Some text")?;
    s.separator()?;
    s.text("Some other text")?;
    Ok(())
}

Get clipboard text from the system clipboard.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    println!("Current clipboard text: {}", s.clipboard_text());
    Ok(())
}

Set clipboard text to the system clipboard.

Errors

If the renderer fails to retrieve the clipboard text, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.set_clipboard_text("Copied to clipboard!")?;
    Ok(())
}

Open a URL in the default system browser.

Errors

If the renderer fails to launch an external application, then an error is returned. Note, there is no way to know if the URL opened successfully or not. An Ok result only means an application was successfully launched to handle the URL.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.button("Open Homepage")? {
        s.open_url("https://example.com")?;
    }
    Ok(())
}

Returns the reference to the current theme.

Returns the a mutable reference to the current theme.

Sets a new theme.

Draw a text field to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text_field("Text Field", &mut self.text_field)?;
    Ok(())
}

Draw a text field with a placeholder hint to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.advanced_text_field(
        "Filtered Text Field w/ hint",
        "placeholder",
        &mut self.text_field,
        Some(char::is_numeric),
    )?;
    Ok(())
}

Draw a text area field to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text_area("Text Area", 200, 100, &mut self.text_area)?;
    Ok(())
}

Draw a text area field with a placeholder hint to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.advanced_text_area(
        "Filtered Text Area w/ hint",
        "placeholder",
        200,
        100,
        &mut self.text_area,
        Some(char::is_alphabetic),
    )?;
    Ok(())
}

Draw a select box the current canvas that returns true when selection is changed.

Maximum displayed count of 100.

Errors

If the renderer fails to draw to the current render target, or if displayed_count is greater than MAX_DISPLAYED then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    let items = ["Item 1", "Item 2", "Item 3"];
    let displayed_count = 4;
    if s.select_box("Select Box", &mut self.select_box, &items, displayed_count)? {
        // selection changed
    }
    Ok(())
}

Draw a select list to the current canvas with a scrollable region that returns true when selection is changed.

Errors

If the renderer fails to draw to the current render target, or if displayed_count is greater than MAX_DISPLAYED then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    let items = ["Item 1", "Item 2", "Item 3"];
    let displayed_count = 4;
    if s.select_list("Select List", &mut self.select_list, &items, displayed_count)? {
        // Selection  changed
    }
    Ok(())
}

Draw a draggable number widget to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.drag("Drag Int", &mut self.int, 1)?;
    s.drag("Drag Float", &mut self.float, 0.005)?;
    Ok(())
}

Draw an advanced draggable number widget to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.advanced_drag(
        "Advanced Drag",
        &mut self.advanced_drag,
        0.005,
        0.0,
        1.0,
        Some(|val| format!("{:.3}", val).into()),
    )?;
    Ok(())
}

Draw a slider widget to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.slider("Slider Int", &mut self.int, -5, 5)?;
    s.slider("Slider Float", &mut self.float, 0.0, 1.0)?;
    Ok(())
}

Draw an advanced slider widget to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Panics

Panics if value, min, or max can not be cast to a floating point value.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.advanced_slider(
        "Advanced Slider",
        &mut self.advanced_slider,
        0.0,
        1.0,
        Some(|val| format!("ratio = {:.3}", val).into()),
    )?;
    Ok(())
}

Return the dimensions of given text for drawing to the current canvas.

Errors

If the renderer fails to load the current font, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    let text = "Some text";
    let (w, h) = s.size_of(text)?;
    // Draw a box behind the text
    s.rect(rect![s.cursor_pos() - 10, w as i32 + 20, h as i32 + 20]);
    s.text(text)?;
    Ok(())
}

Draw body text to the current canvas.

Returns the rendered (width, height) of the text, including any newlines or text wrapping.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text("Text")?;
    Ok(())
}

Draw heading text to the current canvas.

Returns the rendered (width, height) of the text, including any newlines or text wrapping.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.heading("Heading")?;
    Ok(())
}

Draw monospace text to the current canvas.

Returns the rendered (width, height) of the text, including any newlines or text wrapping.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.monospace("Monospace")?;
    Ok(())
}

Draw transformed text to the current canvas, optionally rotated about a center by angle or flipped. angle can be in radians or degrees depending on AngleMode.

Returns the rendered (width, height) of the text, including any newlines or text wrapping.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.angle_mode(AngleMode::Degrees);
    let angle = 10.0;
    let center = point!(10, 10);
    s.text_transformed("Transformed text", angle, center, Flipped::Horizontal)?;
    Ok(())
}

Draw bulleted text to the current canvas.

Returns the rendered (width, height) of the text, including any newlines or text wrapping.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.bullet("Bulleted text")?;
    Ok(())
}

Draw a text menu to the current canvas which returns true when clicked.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Draw a collapsing text tree to the current canvas which returns true when the bullet is not collapsed.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Draw a collapsing header to the current canvas which returns true when the tree is not collapsed.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Draw help marker text that, when hovered, displays a help box with text to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.help_marker("Help marker icon w/ tooltip")?;
    Ok(())
}

Draw tooltip box at the mouse cursor with text to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text("Hover me")?;
    if s.hovered() {
        s.tooltip("Basic tooltip")?;
    }
    Ok(())
}

Draw an advanced tooltip box at the mouse cursor to the current canvas. It accepts a closure that is passed &mut PixState which you can use to draw all the standard drawing primitives and change any drawing settings. Settings changed inside the closure will not persist, similar to PixState::with_texture.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text("Hover me")?;
    if s.hovered() {
        s.advanced_tooltip(
            "Tooltip",
            rect![s.mouse_pos(), 200, 100],
            |s: &mut PixState| {
                s.background(Color::CADET_BLUE);
                s.bullet("Advanced tooltip")?;
                Ok(())
            },
        )?;
    }
    Ok(())
}

Draw a button to the current canvas that returns true when clicked.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.button("Button")? {
        // was clicked
    }
    Ok(())
}

Draw a text link to the current canvas that returns true when clicked.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    if s.link("Link")? {
        // was clicked
    }
    Ok(())
}

Draw a checkbox to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.checkbox("Checkbox", &mut self.checkbox)?;
    Ok(())
}

Draw a set of radio buttons to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.radio("Radio 1", &mut self.radio, 0)?;
    s.radio("Radio 2", &mut self.radio, 1)?;
    s.radio("Radio 3", &mut self.radio, 2)?;
    Ok(())
}

Render an arrow aligned with the current font size.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Draw a scrollable region to the current canvas.

Errors

If the renderer fails to draw to the current render target, then an error is returned.

Push a new seed to the UI ID stack. Helps in generating unique widget identifiers that have the same text label. Pushing a unique ID to the stack will seed the hash of the label.

Pop a seed from the UI ID stack.

Returns the current UI rendering position.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    let mut pos = s.cursor_pos();
    pos.offset_y(20);
    s.set_cursor_pos(pos);
    s.text("Some text, offset down by 20 pixels")?;
    Ok(())
}

Set the current UI rendering position.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.set_cursor_pos(s.center()?);
    s.rect_mode(RectMode::Center);
    s.text("Centered text")?;
    Ok(())
}

Set the current UI rendering position column offset.

Clears the current UI rendering position column offset.

Returns whether the last item drawn is hovered with the mouse.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text("Hover me")?;
    if s.hovered() {
        s.tooltip("I'm a tooltip!");
    }
    Ok(())
}

Returns whether the last item drawn was clicked with the left mouse button.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text("Hover me")?;
    if s.clicked() {
        println!("I was clicked!");
    }
    Ok(())
}

Returns whether the last item drawn was double-clicked with the left mouse button.

Example
fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    s.text("Hover me")?;
    if s.dbl_clicked() {
        println!("I was double clicked!");
    }
    Ok(())
}

Return usable UI width given the current UI cursor position and padding clamped to i32.

Errors

If the current window target has been closed or is invalid, then an error is returned.

Return usable UI height given the current UI cursor position and padding clamped to i32.

Errors

If the current window target has been closed or is invalid, then an error is returned.

Trait Implementations

Formats the value using the given formatter. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.