LoginSignup
1
0

More than 1 year has passed since last update.

SDL2 のサンプルプログラムを試す

Last updated at Posted at 2022-12-10

環境

  • Ubuntu22.04
  • Ubuntu20.04

インストール

さくっと公式パッケージからインストールしました。


$ sudo apt-get install libsdl2-dev
$ sudo apt-get install libsdl2-image-dev libsdl2-mixer-dev libsdl2-net-dev libsdl2-ttf-dev

サンプルプログラム

元ネタはこちら
https://solarianprogrammer.com/2015/01/22/raspberry-pi-raspbian-getting-started-sdl-2/

png ファイルを表示するプログラムです。
今回は、png ファイルは WikiMedia から持ってきました。

https://commons.wikimedia.org/wiki/File:Yes-check-icon-transparent.png
これをダウンロード
image.png

プログラムは元ネタから簡略化して以下のようにしました。

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>

SDL_Texture* load_texture(const char* fname, SDL_Renderer *renderer);

int main(int argc, char** argv) {
    SDL_Init(SDL_INIT_VIDEO);
    // 512 x 512 size window
    SDL_Window* window = SDL_CreateWindow("SDL2 TestDraw", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                                          512, 512, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    IMG_Init(IMG_INIT_PNG);

    // Clear the window with default color: RGB=(0,30,0)  and Alpha=255
    SDL_SetRenderDrawColor(renderer, 0, 30, 0, 255);
    SDL_RenderClear(renderer);

    // image file load
    SDL_Surface *image = IMG_Load("Yes-check-icon-transparent.png");
    SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, image);
    SDL_FreeSurface(image);

    // image show with size
    SDL_Rect dest_rect;
    dest_rect.x = 0; dest_rect.y = 0;
    dest_rect.w = 512; dest_rect.h = 512;
    SDL_RenderCopy(renderer, texture, NULL, &dest_rect);

    // Update window, keep 5 sec and quit 
    SDL_RenderPresent(renderer);
    SDL_Delay(5000);
    SDL_DestroyTexture(texture);
    IMG_Quit();
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

コンパイル

元ネタではこのようになってましたが

$ g++ -std=c++14 -Wall -pedantic test.cpp -o test `sdl2-config --cflags --libs` -lSDL2_image

以下で通りました

$ g++ test.cpp -o test -lSDL2  -lSDL2_image

実行

$ ./test

OKです。

image.png

Cでコンパイルする

test.c を test.cpp からコピーしてきて、ソースコードの以下の一行を削除

#include <iostream>

以下でコンパイル

$ cc test.c -o test -lSDL2  -lSDL2_image

実行

$ ./test

OKでした!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0