How to render SDL2 texture into GTK3+ window?

2020-02-16 03:33发布

问题:

I am creating a music player and trying to use GTK3+ for creating user interface. I am using SDL_CreateWindowFrom function to let SDL2 use GTK3+ window rather than creating one but cann't figure out the steps I need to follow in order to render the SDL2 textures into GTK3+ window.

Code getting GTK3 window ID

window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window), "---");
gtk_widget_show(window);
gdkWin = gtk_widget_get_window(GTK_WIDGET(window));
data->playContext->winID = GDK_WINDOW_XID(gdkWin);
gtk_main(); 

Code Setting SDL2 window

playContext->display->window = SDL_CreateWindowFrom((const void *)playContext->winID);
playContext->display->renderer = SDL_CreateRenderer(playContext->display->window, -1, playContext->display->render_flags);

Code Rendering SDL2 textures

SDL_RenderClear(playContext->display->renderer);
SDL_RenderCopy(playContext->display->renderer, playContext->textureQ.head->bmp, NULL, NULL);
SDL_RenderPresent(playContext->display->renderer);

回答1:

Since example you put is effectively incomplete even on most important bits (e.g. renderer creation flags), and you don't specify which part gives you a problem, here is my example (which, on my system, works on both gtk2 and gtk3 - I wouldn't vouch it is completely fine though):

#include <stdio.h>
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <SDL.h>
#include <stdbool.h>

static SDL_Window *sdl_window;
static SDL_Renderer *sdl_renderer;
static SDL_Surface *sdl_surface;
static GtkWindow *gtk_window;
static GtkWidget *gtk_da;
static void *gdk_window;
static void *window_id;

static gboolean idle(void *ud) {
    (void)ud;
    if(!sdl_window) {
        printf("creating SDL window for window id %p\n", window_id);
        sdl_window = SDL_CreateWindowFrom(window_id);
        printf("sdl_window=%p\n", sdl_window);
        if(!sdl_window) {
            printf("%s\n", SDL_GetError());
        }
        sdl_renderer = SDL_CreateRenderer(sdl_window, -1, 0);
        printf("sdl_renderer=%p\n", sdl_renderer);
        if(!sdl_renderer) {
            printf("%s\n", SDL_GetError());
        }
    } else {
        SDL_SetRenderDrawColor(sdl_renderer, 255, 0, 0, 255);
        SDL_RenderClear(sdl_renderer);
        SDL_RenderPresent(sdl_renderer);
    }
    return true;
}

int main(int argc, char **argv) {
    gtk_init(&argc, &argv);
    gtk_window = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(gtk_window, "test");

    gtk_da = gtk_drawing_area_new();
    gtk_container_add(GTK_CONTAINER(gtk_window), gtk_da);
    gtk_widget_show_all(GTK_WIDGET(gtk_window));

    gdk_window = gtk_widget_get_window(GTK_WIDGET(gtk_da));
    window_id = (void*)(intptr_t)GDK_WINDOW_XID(gdk_window);

    SDL_Init(SDL_INIT_VIDEO);

    g_idle_add(&idle, 0);
    gtk_main();
    return 0;
}


标签: gtk3 sdl-2