Para este exemplo construirase un sinxelo visor de imaxes usando Clutter. Aprenderá:
Como dimensionar e posicionar varios ClutterActor
Como posicionar unha imaxe nun ClutterActor
Como facer transicións sinxelas usando o framework de animacións Clutter.
Como facer que os ClutterActor
respondan a eventos do rato
Como obter nomes de ficheiros dun cartafol
Clutter is a library for creating dynamic user interfaces using OpenGL for hardware acceleration. This example demonstrates a small, but central, part of the Clutter library to create a simple but attractive image viewing program.
To help us reach our goal we will be utilising a few other common pieces of GLib as well. Most importantly, we'll use one GPtrArray
, a dynamic array of pointers, to hold the file path names. We will also use GDir
, a utility for working with directories, to access our image directory and gather file paths.
Antes de comezar a programar, deberá configurar un proxecto novo en Anjuta. Isto creará todos os ficheiros que precise para construír e executar o código máis adiante. Tamén é útil para manter todo ordenado.
Inicie Anjuta e prema
Choose
Asegúrese que
Active
Prema
#include ]]>
O novo visor de imaxes móstralle ao usuario un muro de imaxes.
Cando se fai clic sobre unha imaxe, esta anímase para ocupar todo o área de visualización. Cando se fai clic sobre unha imaxe que ten o foco volverá á súa posición orixinal usando unha animación da mesma duración de 500 milisegundos.
O seguinte fragmento de código contén moitas definicións e variábeis que se usarán nas seguintes seccións. Úseo como referencia para as próximas seccións. Copie este código ao principio de
#include
#define STAGE_WIDTH 800
#define STAGE_HEIGHT 600
#define THUMBNAIL_SIZE 200
#define ROW_COUNT (STAGE_HEIGHT / THUMBNAIL_SIZE)
#define COL_COUNT (STAGE_WIDTH / THUMBNAIL_SIZE)
#define THUMBNAIL_COUNT (ROW_COUNT * COL_COUNT)
#define ANIMATION_DURATION_MS 500
#define IMAGE_DIR_PATH "./berlin_images/"
static GPtrArray *img_paths;
static ClutterPoint unfocused_pos;
]]>
Comezaremos ollando a función main()
. Logo discutiremos as outras seccións de código en detalle. Cambie o ficheiro main()
. Pode elminar a función create_window()
xa que non a necesitamos neste exemplo.
Liña 4: ClutterColor
é definido estabelecendo o valor a vermello, verde, azul ou transparente (alfa). O rango de valores están entre 0-255. Para a transparencia 255 é opaco.
Liña 7: Debe inicializar Clutter. Se esqueceu isto, haberá moitos erros estraños. Está avisado.
Lines 10‒14: Here we create a new ClutterStage
. We then set the size using the defines from the previous section and the address of the ClutterColor
we just defined.
Un CluterStage
é o nivel superior dun ClutterActor
no que se localizan outros ClutterActor
.
Line 16: Here we call our function for getting the image file paths. We'll look at this in a bit.
Lines 18‒49: This is where we set up the ClutterActor
s, load the images and place them into their spot in the image wall. We will look at this in detail in the next section.
Line 52: Show the stage and all its children, meaning our images.
Line 55: Start the Clutter main loop.
En Clutter, un actor é o elemento visual máis básico. Basicamente, todo o que ve é un actor.
Nesta sección, imos botar unha ollada máis polo miúdo ao búcle usado para configurar os ClutterActor
s que mostrarán as nosas imaxes.
Line 7: Here we want to get the path at the nth location in the GPtrArray
that is holding our image path names. The nth position is calculated based on row
and col
.
Line 8‒23: This is where we actually create the ClutterActor
and place the image into the actor. The first argument is the path which we access through our GSList
node. The second argument is for error reporting but we are ignoring that to keep things short.
Line 47: This adds the ClutterActor
to the stage, which is a container. It also assumes ownership of the ClutterActor
which is something you'll want to look into as you get deeper into GNOME development. See the GObject
documentation for the gory details.
Botemos unha pequena ollada a Clutter para ver como obter os nomes dos ficheiros desde o noso cartafol de imaxes.
message);
g_clear_error(&error);
return;
}
img_paths = g_ptr_array_new_with_free_func (g_free);
const gchar *filename = g_dir_read_name(dir);
while(filename)
{
if(g_str_has_suffix(filename, ".jpg") || g_str_has_suffix(filename, ".png"))
{
gchar *path = g_build_filename(IMAGE_DIR_PATH, filename, NULL);
g_ptr_array_add (img_paths, path);
}
filename = g_dir_read_name(dir);
}
}]]>
Lines 5 and 12: This opens our directory or, if an error occurred, returns after printing an error message.
Lines 16‒25: The first line gets another file name from the GDir
we opened earlier. If there was an image file (which we check by looking at its extension, ".png" or ".jpg") in the directory we proceed to prepend the image directory path to the filename and prepend that to the list we set up earlier. Lastly we attempt to get the next path name and reenter the loop if another file was found.
Vote unha ollada ao tamaño e ao posicionamento dos ClutterActor
e a como se deixa listo o ClutterActor
para a interacción do usuario.
Liña 7: configurar un actor como «reactivo» significa que reacciona aos eventos tales como button-press-event
no noso caso. Para o mural de fotos, todos os ClutterActor
do mural deben ser inicialmente reactivos.
Liñas 9-12: agora conéctase o evento button-press-evento
á chamada actor_clicked_cb
que veremos máis adiante.
Neste punto obteremos un muro de imaxes que están listas para ser mostradas.
Lines 1‒4: We have to make sure our callback function matches the signature required for the button_clicked_event
signal. For our example, we will only use the first argument, the ClutterActor
that is actually clicked.
A few words on the arguments we are not using in this example. The ClutterEvent
is different depending on what event is being handled. For example, a key event produces a ClutterKeyEvent
from which you can get the key being pressed among other information. For mouse click events you get a ClutterButtonEvent
from which you can get the x
and y
values. See the Clutter documentation for other ClutterEvent
types.
The user_data
is what one uses to pass data into the function. A pointer to any data type can be passed in. If you need multiple data to be passed into the callback, you can place the data into a struct and pass its address in.
Line 7: We set up a static flag to track which state we are in: wall mode or focus mode. We start out in wall mode so no image has focus. Thus, we set the flag to FALSE
initially.
Line 12‒14: These set the image actors to receive events if they are focused.
Line 16‒17: Here we set the animation duration and save the current state.
Lines 21‒23: Reaching this code means that one image currently has focus and we want to return to wall mode. Setting a position on a ClutterActor
begins an animation with the duration that we set in line 17.
Line 24: Reaching this line of code means we are currently in the wall state and are about to give a ClutterActor
focus. Here we save the starting position so that we can return to it later.
Line 25: Setting the ClutterActor
's reactive
property to TRUE
makes this ClutterActor
react to events. In this focused state the only ClutterActor
that we want to receive events will be the ClutterActor
being viewed. Clicking on the ClutterActor
will return it to its starting position.
Lines 27‒36: This is where we save the current position of the image, set it to receive events and then make it appear above the other images and start animating it to fill the stage.
Line 39: Here we restore the easing state to what was set before we changed it in line 16.
Line 42: Here we toggle the is_focused
flag to the current state.
As mentioned previously, the ClutterActor
s with higher depth
values receive events but can allow ClutterActor
s below them to also receive events. Returning TRUE
will stop events from being passed down, while FALSE
will pass events down.
Remember, however, that to receive events the ClutterActor
s must be set reactive
.
Todo o código debería estar listo para executarse. Todo o que necesita son algunhas imaxes para cargar. De maneira predeterminada, as imaxes cárganse desde o cartafol #define IMAGE_DIR_PATH
do principio para que faga referencia ao seu cartafol de fotos, ou crear un cartafol
Cando teña que facer iso, prema
Se non o fixo aínda, seleccione o aplicativo
Se ten problemas ao executar este titorial compare o seu código con este código de referencia.