[Solved] My cairo-rs program is not working as intended

I apologize if this is outside the forum's scope, but I'm flummoxed.

I've been learning Rust over the past month or so and I decided to take a break by trying out cairo-rs.

I started out with the first tutorial here, the one that produces a red square.

That worked fine, but the next tutorial involved creating random lines which I wasn't interested in doing. But I thought I figured out enough looking at it to do my own program: draw a single black line across a white canvas. So I wrote the following:

extern crate cairo;
use cairo::{Context, Format, ImageSurface};
use std::fs::File;

fn main() {
    let surface = ImageSurface::create(Format::ARgb32, 600, 600)
        .expect("Couldn’t create surface");
    let context = Context::new(&surface);

    context.set_source_rgb(1.0, 1.0, 1.0);
    context.paint();

    context.set_source_rgb(0.0, 0.0, 0.0);
    context.line_to(0.0, 600.0);
    context.stroke();

    let mut file = File::create("line_out.png")
        .expect("Couldn't create file.");
    surface.write_to_png(&mut file)
        .expect("Couldn't write to file.");
}

I run it and get no errors, and it gives me the white canvas... but no black line. I'm not going to post the output image as it's just a white square, there would be nothing to see if I put it up here. :-p

So there are no compiler errors, I don't get warnings in my IDE about anything and I've installed all the dependencies as far as I know. I'm stumped as to what the problem could be.

Where does the line start from? It might be natural to assume that it starts at (0,0) but apparently that is not the case. I added a call to move_to and then changed the coordinates in line_to to create a diagonal line across the image and it worked for me after that.

use cairo::{Context, Format, ImageSurface};
use std::fs::File;

fn main() {
    let surface =
        ImageSurface::create(Format::ARgb32, 600, 600).expect("Couldn’t create surface");
    let context = Context::new(&surface);

    context.set_source_rgb(1.0, 1.0, 1.0);
    context.paint();

    context.set_source_rgb(0.0, 0.0, 0.0);
    context.move_to(0.0, 0.0);          // ADDED THIS LINE
    context.line_to(600.0, 600.0);      // CHANGED THIS LINE
    context.stroke();

    let mut file = File::create("line_out.png").expect("Couldn't create file.");
    surface
        .write_to_png(&mut file)
        .expect("Couldn't write to file.");
}

Thank you! I was a bit confused by some of the documentation. In retrospect I should have taken a more thorough look at it.

Regardless, thanks. : - )

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.