基于gtk的imshow:用gtk读取并显示图像
gtk实现imshow,最naive的做法是用gtk的组件去读取图像,然后show出来;后续再考虑用GTK显示用别的方式例如stb image读取的图像。先前基于GDI实现imshow时也是这一思路,先能show出来给自己一点信心。
官方代码
gtk官方文档提供了这个例子,并且show出来的图像和原图大小一致。
#include <gtk/gtk.h>
static void activate (GtkApplication *app, gpointer user_data)
{
GtkWidget *window;
GtkWidget *image;
/*Create a window with a title and a default size*/
window = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (window), "Welcome to GNOME");
//gtk_window_set_default_size (GTK_WINDOW (window), 300, 300);
const char* im_pth = "/home/zz/work/libfc/imgs/Lena.png";
image = gtk_image_new_from_file (im_pth);
gtk_container_add (GTK_CONTAINER (window), GTK_WIDGET (image));
gtk_widget_show_all (GTK_WIDGET (window));
}
int main (int argc, char **argv)
{
GtkApplication *app;
int status;
app = gtk_application_new ("org.gtk.example",G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
status = g_application_run (G_APPLICATION (app), argc, argv);
g_object_unref (app);
return status;
}
效果:
简单封装
从imshow的用户来讲,ta只需要传入图片路径、图片标题,就应该得到显示结果。因此可以把上述代码进行封装。使用了全局变量my_window
,这是因为回调函数无法传入额外的参数,并且后续要给窗口绑定更多的参数。
#include <gtk/gtk.h>
#include <stdlib.h>
typedef struct MyWindow {
const char* im_pth;
const char* title;
} MyWindow;
MyWindow my_window;
static void activate (GtkApplication *app, gpointer user_data)
{
GtkWidget *window;
GtkWidget *image;
/*Create a window with a title and a default size*/
window = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (window), my_window.title);
//gtk_window_set_default_size (GTK_WINDOW (window), 300, 300);
image = gtk_image_new_from_file (my_window.im_pth);
gtk_container_add (GTK_CONTAINER (window), GTK_WIDGET (image));
gtk_widget_show_all (GTK_WIDGET (window));
}
void show_image_gtk_temp()
{
GtkApplication *app;
int status;
app = gtk_application_new ("org.gtk.example",G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
status = g_application_run (G_APPLICATION (app), 0, NULL);
g_object_unref (app);
}
void gtk_show_image_v1(const char* im_pth, const char* title) {
my_window.im_pth = im_pth;
my_window.title = title;
show_image_gtk_temp();
}
int main() {
const char* im_pth = "/home/zz/work/libfc/imgs/fruits.jpg";
const char* title = "fruit";
gtk_show_image_v1(im_pth, title);
return 0;
}
参考
https://developer.gnome.org/gnome-devel-demos/stable/image.c.html.en
Greatness is never a given, it must be earned.