Created
March 3, 2020 22:42
-
-
Save 17cupsofcoffee/1553b49faf4def7055855ccb29844a20 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use ggez::{event, graphics, nalgebra, Context, GameResult}; | |
struct MainState { | |
spritebatch: graphics::spritebatch::SpriteBatch, | |
} | |
impl MainState { | |
fn new(ctx: &mut Context) -> GameResult<MainState> { | |
let width: f32 = 128.0; | |
let height: f32 = 128.0; | |
// Draw in canvas a green rectangle centered in a red area | |
let canvas = graphics::Canvas::new( | |
ctx, | |
width as u16, | |
height as u16, | |
ggez::conf::NumSamples::One, | |
)?; | |
graphics::set_canvas(ctx, Some(&canvas)); | |
let red = graphics::Color::new(1.0, 0.0, 0.0, 1.0); | |
let green = graphics::Color::new(0.0, 1.0, 0.0, 1.0); | |
graphics::clear(ctx, red); | |
let rect = graphics::Mesh::new_rectangle( | |
ctx, | |
graphics::DrawMode::fill(), | |
graphics::Rect::new(width / 4.0, height / 4.0, width / 2.0, height / 2.0), | |
green, | |
)?; | |
graphics::draw(ctx, &rect, (nalgebra::Point2::new(0.0, 0.0),))?; | |
// graphics::present(ctx)?; | |
graphics::set_canvas(ctx, None); | |
// let data = canvas.image().to_rgba8(ctx)?; <= every values are 0 | |
let spritebatch = graphics::spritebatch::SpriteBatch::new(canvas.image().clone()); | |
Ok(MainState { spritebatch }) | |
} | |
} | |
impl event::EventHandler for MainState { | |
fn update(&mut self, _ctx: &mut Context) -> GameResult { | |
Ok(()) | |
} | |
fn draw(&mut self, ctx: &mut Context) -> GameResult { | |
graphics::clear(ctx, graphics::BLACK); | |
self.spritebatch.clear(); | |
self.spritebatch | |
.add(graphics::DrawParam::new().dest(nalgebra::Point2::new(0.0, 0.0))); | |
graphics::draw( | |
ctx, | |
&self.spritebatch, | |
graphics::DrawParam::new().dest(nalgebra::Point2::new(0.0, 0.0)), | |
)?; | |
graphics::present(ctx)?; | |
Ok(()) | |
} | |
} | |
pub fn main() -> GameResult { | |
let cb = ggez::ContextBuilder::new("draw in image", "ggez"); | |
let (ctx, event_loop) = &mut cb.build()?; | |
let state = &mut MainState::new(ctx)?; | |
event::run(ctx, event_loop, state) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment