Exempelprogram: Skapa en klocka med Cairo

Nu då vi täckt grunderna med att rita i Cairo kan vi försöka sätta ihop allting och skapa ett enkelt program som faktiskt gör något. Följande exempel använder Cairo för att skapa en anpassad komponent Clock. Klockan har en sekundvisare, en minutvisare och en timvisare, och uppdaterar sig själv varje sekund.

Källkod

As before, almost all of the interesting stuff is done in the draw function on_draw(). Before we dig into the draw function, notice that the constructor for the Clock widget connects a handler function on_timeout() to a timer with a timeout period of 1000 milliseconds (1 second). This means that on_timeout() will get called once per second. The sole responsibility of this function is to invalidate the window so that gtkmm will be forced to redraw it.

Låt oss nu ta en titt på koden som utför det faktiska ritandet. Den första delen av on_draw() bör vara ganska bekant nu. Detta exempel skalar igen koordinatsystemet till en enhetskvadrat så att det är lättare att rita klockan som en procentsats av fönsterstorleken, så att den automatiskt kommer skalas när fönsterstorleken justeras. Vidare skalas och flyttas koordinatsystemet så att koordinaten (0, 0) är i mitten av fönstret.

The function Cairo::Context::paint() is used here to set the background color of the window. This function takes no arguments and fills the current surface (or the clipped portion of the surface) with the source color currently active. After setting the background color of the window, we draw a circle for the clock outline, fill it with white, and then stroke the outline in black. Notice that both of these actions use the _preserve variant to preserve the current path, and then this same path is clipped to make sure that our next lines don't go outside the outline of the clock.

Efter att ha ritat konturen går vi runt klockan och ritar streck för varje timme, med ett större streck vid 12, 3, 6 och 9. Slutligen är vi redo att implementera klockans tidtagande, vilket helt enkelt innefattar att få de aktuella värdena för timmar, minuter och sekunder, och rita visarna på rätt vinklar.