目次 - API(機能別) - サーフェイスの生成と単純な描画 - SDL_CreateRGBSurfaceWithFormatFrom

SDL_CreateRGBSurfaceWithFormatFrom

既存のピクセルデータから新しいRGBサーフェイスを生成する

構文

SDL_Surface* SDL_CreateRGBSurfaceWithFormatFrom(void* pixels, int width, int height, int depth, int pitch, Uint32 format)

引数

pixels既存のピクセルデータへのポインタ
widthサーフェイスの幅
heightサーフェイスの高さ
depthサーフェイスのビット深度
pitchpixelsの水平方向のバイト数
formatサーフェイスのピクセル形式

戻り値

成功のとき生成されたSDL_Surface, 失敗のときNULLを戻す. SDL_GetError()を呼んで詳細を知ることができる.

サンプルコード

// stb_image.hを使って読み込んだ画像ファイルからSDL_Surface*を生成するサンプル
// (https://github.com/nothings/stb/)

// stb_imageに要求する出力のカラー形式
// αチャネルを求めない/必要ないならばSTBI_rgbを使うこと
int req_format = STBI_rgb_alpha;
int width, height, orig_format;
unsigned char* data = stbi_load("./test.png", &width, &height, &orig_format, req_format);
if (data == NULL) {
    SDL_Log("画像の読み込みに失敗した: %s", stbi_failure_reason());
    exit(1);
}

int depth, pitch;
Uint32 pixel_format;
if (req_format == STBI_rgb) {
    depth = 24;
    pitch = 3*width; // 1ピクセルあたり3byte * 1行のピクセル数
    pixel_format = SDL_PIXELFORMAT_RGB24;
} else { // STBI_rgb_alpha (RGBA)
    depth = 32;
    pitch = 4*width;
    pixel_format = SDL_PIXELFORMAT_RGBA32;
}

SDL_Surface* surf = SDL_CreateRGBSurfaceWithFormatFrom((void*)data, width, height,
                                                       depth, pitch, pixel_format);

if (surf == NULL) {
    SDL_Log("サーフェイスの生成に失敗した: %s", SDL_GetError());
    stbi_image_free(data);
    exit(1);
}

// ... ここでサーフェイスを使う ...
// ...

// サーフェイスが必要なくなったら解放する...
SDL_FreeSurface(surf);
// .. *そして* サーフェイスで使ったデータも!
stbi_image_free(data);

詳細

メモリを確保できなかったときはNULLを戻す.

ピクセルデータはコピーされない. ピクセルデータは自動的に管理されない. つまり, ピクセルデータを解放する前にサーフェイスを解放する必要がある.

バージョン

この関数はSDL 2.0.5以降で使える.

関連項目(関数)

SDL_CreateRGBSurfaceFrom
SDL_CreateRGBSurfaceWithFormat
SDL_FreeSurface

SDL Wikiへのリンク

SDL_CreateRGBSurfaceWithFormatFrom - SDL Wiki