Skip to content

Instantly share code, notes, and snippets.

@stevensonmt
Created October 10, 2019 04:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevensonmt/e2cbe95bfb4920e58adc433b4c4fa7df to your computer and use it in GitHub Desktop.
Save stevensonmt/e2cbe95bfb4920e58adc433b4c4fa7df to your computer and use it in GitHub Desktop.
sdl2 transparent window setting applies to all elements
fn run(font_path: &Path) -> Result<(), String> {
let sdl_context = sdl2::init()?;
let video_subsys = sdl_context.video()?;
let ttf_context = sdl2::ttf::init().map_err(|e| e.to_string())?;
let mut window = video_subsys
.window("SDL2_TTF Example", SCREEN_WIDTH, SCREEN_HEIGHT)
.position_centered()
.opengl()
.build()
.map_err(|e| e.to_string())?;
window.set_opacity(0.5)?;
let mut canvas = window.into_canvas().build().map_err(|e| e.to_string())?;
let texture_creator = canvas.texture_creator();
// Load a font
let mut font = ttf_context.load_font(font_path, 64)?;
font.set_style(sdl2::ttf::FontStyle::BOLD);
// render a surface, and convert it to a texture bound to the canvas
let surface = font
.render("Hello Rust!")
.shaded(Color::RGB(255, 0, 0), Color::RGBA(0, 0, 0, 255))
.map_err(|e| e.to_string())?;
let texture = texture_creator
.create_texture_from_surface(&surface)
.map_err(|e| e.to_string())?;
canvas.set_draw_color(Color::RGBA(0, 0, 0, 255));
canvas.clear();
let TextureQuery { width, height, .. } = texture.query();
// If the example text is too big for the screen, downscale it (and center irregardless)
let padding = 64;
let target = get_centered_rect(
width,
height,
SCREEN_WIDTH - padding,
SCREEN_HEIGHT - padding,
);
canvas.copy(&texture, None, Some(target))?;
canvas.present();
'mainloop: loop {
for event in sdl_context.event_pump()?.poll_iter() {
match event {
Event::KeyDown {
keycode: Some(Keycode::Escape),
..
}
| Event::Quit { .. } => break 'mainloop,
_ => {}
}
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment