Image extension

Creating Images

Create Image objects in memory and draw them in a Window.

The first Image extension

Image belongs to an extension, rather than Core. Write #include <small/image.h> at the top. Small IDE sees this include and automatically links the Image extension.

Try it first

Example · example1.cpp
#include <small/image.h>

void small_main()
{
    Image image(160, 120, Blue);

    for (int y = 20; y < 100; y++)
        for (int x = 20; x < 140; x++)
            image.set_pixel(x, y, Yellow);

    Window window;
    window.open(640, 400);

    while (window.is_open())
    {
        window.clear(Black);
        draw_image(window, image, 80, 80);
        draw_image(window, image, 300, 80, 240, 180);
        window.show();
    }
}

Image and Window are different things

Image owns image data and provides operations intrinsic to an image, such as width(), height(), and pixel(). draw_image(window, image, ...) is a free function because it connects Image and Window.

Omitting a size draws at the original size. Supplying width and height smoothly scales it to that size.

One step further

Example · example2.cpp
#include <small/image.h>

void small_main()
{
    Image image(100, 100, Red);
    print(image.width(), " x ", image.height());

    Window window;
    window.open(400, 250);

    while (window.is_open())
    {
        window.clear(White);
        draw_image(window, image, 150, 75);
        window.show();
    }
}

Extensions are ordinary C++ too

Using Image does not mean learning a new language. You include a header and use ordinary C++ objects and functions.

Exercise — Draw at two sizes

Create a 120 × 80 Green image. Draw it at its original size and twice that size in one window.

Exercise starter · exercise1_starter.cpp
#include <small/image.h>
void small_main()
{
    Image image(120, 80, Green);
    Window window;
    window.open(600, 300);
    while (window.is_open())
    {
        window.clear(Black);
        // Draw twice here.
        window.show();
    }
}

Hint

Use both the four-argument and six-argument forms of draw_image.

show solution
#include <small/image.h>
void small_main()
{
    Image image(120, 80, Green);
    Window window;
    window.open(600, 300);
    while (window.is_open())
    {
        window.clear(Black);
        draw_image(window, image, 40, 60);
        draw_image(window, image, 260, 40, 240, 160);
        window.show();
    }
}

Exercise — Check the size

Create a 64 × 48 image and print its Width and Height.

Exercise starter · exercise2_starter.cpp
#include <small/image.h>
void small_main()
{
    Image image(64, 48, Blue);
    // print its size.
}

Hint

Use print(image.width(), " x ", image.height());.

show solution
#include <small/image.h>
void small_main()
{
    Image image(64, 48, Blue);
    print(image.width(), " x ", image.height());
}
← Previous lessonNext lesson →