SDL在win上安裝

DarkH發表於2024-04-23

官網:https://www.libsdl.org/

1.下載安裝包

下載安裝包 SDL2-devel-2.30.2-VC.zip,然後解壓到指定目錄

此時就安裝完了。簡簡單單。

2.編碼使用demo

編寫CMakeLists.txt

cmake_minimum_required(VERSION 3.28)
project(sdltest01)

set(CMAKE_CXX_STANDARD 20)

set(CMAKE_PREFIX_PATH "C:/Users/Dark/SDL2-2.30.2/")

find_package(SDL2 REQUIRED)

add_executable(${PROJECT_NAME} main.cpp)

target_include_directories(${PROJECT_NAME} PRIVATE ${SDL2_INCLUDE_DIRS})

target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES})

編寫main.cpp

#include <iostream>

#include <SDL.h>

#undef main
int main()
{
    int run = 1;
    SDL_Window *window = NULL;
    SDL_Renderer *renderer = NULL;
    SDL_Texture *texture = NULL;
    SDL_Rect rect; // 長方形,原點在左上角
    rect.w = 50;    //方塊大小
    rect.h = 50;

    SDL_Init(SDL_INIT_VIDEO);//初始化函式,可以確定希望啟用的子系統

    window = SDL_CreateWindow("2 Window",
                              SDL_WINDOWPOS_UNDEFINED,
                              SDL_WINDOWPOS_UNDEFINED,
                              640,
                              480,
                              SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);// 建立視窗

    if (!window)
    {
        return -1;
    }
    renderer = SDL_CreateRenderer(window, -1, 0);//基於視窗建立渲染器
    if (!renderer)
    {
        return -1;
    }

    texture = SDL_CreateTexture(renderer,
                                SDL_PIXELFORMAT_RGBA8888,
                                SDL_TEXTUREACCESS_TARGET,
                                640,
                                480); //建立紋理

    if (!texture)
    {
        return -1;
    }

    int show_count = 0;
    while (run)
    {
        rect.x = rand() % 600;
        rect.y = rand() % 400;

        SDL_SetRenderTarget(renderer, texture); // 設定渲染目標為紋理
        SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); // 紋理背景為黑色
        SDL_RenderClear(renderer); //清屏

        SDL_RenderDrawRect(renderer, &rect); //繪製一個長方形
        SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255); //長方形為白色
        SDL_RenderFillRect(renderer, &rect);

        SDL_SetRenderTarget(renderer, NULL); //恢復預設,渲染目標為視窗
        SDL_RenderCopy(renderer, texture, NULL, NULL); //複製紋理到CPU

        SDL_RenderPresent(renderer); //輸出到目標視窗上
        SDL_Delay(300);
        if(show_count++ > 30)
        {
            run = 0;        // 不跑了
        }
    }

    SDL_DestroyTexture(texture);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window); //銷燬視窗
    SDL_Quit();
    return 0;
}

執行時自己把SDL安裝路徑下的lib下的對應的庫,複製到exe目錄下

執行結果會彈個框框出來,然後有個正方形在那裡動來動去,然後就自動關閉框框。

相關文章