FFmpegOpenGL渲染音视频直播技术

「SDL第二篇」窗口渲染

2018-04-07  本文已影响118人  音视频直播技术专家

前言

上一篇文章中我们对SDL作了简单的介绍,重点介绍了如何编译SDL以及如何使用它。在文章的最后我们留下了一个疑问,即虽然我们创建了窗口,但窗口却并没有真正显示出来。

今天我们就来看一看,如何才能让创建的窗口真正的显示出来。

渲染的基本流程

为什么我们上一课中创建了窗口,但它却并没有显示出来呢?其原因是,我们创建的窗口只是逻辑上的窗口,要想让窗口显示出来,我们需要对窗口进行效果渲染,也就是要通过绘制像素的方法,将窗口中的像素全部点亮。

那么如何对窗口进行渲染呢?SDL为我们提供了方便是的API。不过在使用SDL对窗口进行渲染之前,我们要先了解渲染的基本原理。

其基本原理是,首先创建一个window窗口,它是我们要渲染的目标。然后,要有一个渲染上下文,该上下文中一方面存放着要渲染的目标,也就是windows窗口;另一方面是存放着一个缓冲区,该缓冲区用于存放渲染的内容。

渲染的内容可以是点、线、各种图形以及图片,视频的各种组合。这些组合后的内容首先被存放到缓冲区中,最终SDL将缓冲区中的内容渲染到窗口中。

所以渲染的基本流程如下:

常用API

完整例子

我在第一课的代码上,添加了上面几个函数之后,大家可以看到一个全红色的窗口可以显示在我们的面前了。

当然我们还可以在上面画一些图形,比如使用 SDL_RenderDrawLines() 函数在窗口中画一条直线。

#include "SDL.h"
#include <stdio.h>

int main(int argc, char* argv[]) {

    int flag = 1;

    SDL_Window *window;                    // Declare a pointer
    SDL_Renderer *renderer;

    SDL_Init(SDL_INIT_VIDEO);              // Initialize SDL2

    // Create an application window with the following settings:
    window = SDL_CreateWindow(
        "An SDL2 window",                  // window title
        SDL_WINDOWPOS_UNDEFINED,           // initial x position
        SDL_WINDOWPOS_UNDEFINED,           // initial y position
        640,                               // width, in pixels
        480,                               // height, in pixels
        SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS// flags - see below
    );

    // Check that the window was successfully created
    if (window == NULL) {
        // In the case that the window could not be made...
        printf("Could not create window: %s\n", SDL_GetError());
        return 1;
    }

    /* We must call SDL_CreateRenderer in order for draw calls to affect this window. */
    renderer = SDL_CreateRenderer(window, -1, 0);

    /* Select the color for drawing. It is set to red here. */
    SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);

    /* Clear the entire screen to our selected color. */
    SDL_RenderClear(renderer);

    /* Up until now everything was drawn behind the scenes.
       This will show the new, red contents of the window. */
    SDL_RenderPresent(renderer);

    // The window is open: could enter program loop here (see SDL_PollEvent())

    SDL_Delay(3000);  // Pause execution for 3000 milliseconds, for example

    //destory renderer
    if (renderer) {
        SDL_DestroyRenderer(renderer);
    }
    
    // Close and destroy the window
    SDL_DestroyWindow(window);

    // Clean up
    SDL_Quit();
    return 0;
}

小结

本文我向大家介绍了如何将创建的窗口展示出来,并重点介绍了窗口渲染的基本原理以及使用的 SDL API。

后面的文章我将向大家重点介绍如何在窗口绘制一些常用图形。

谢谢!

上一篇 下一篇

猜你喜欢

热点阅读