私は SDL から始めており、紹介を読んでいて、drawPixel
彼らが持っている方法を試しています。私がやっているのはppmビューアです。これまでのところ、配列にrgb値があり、正しく保存されています(配列を印刷して、それらがppmファイル内の位置に対応していることを確認してチェックしました)。SDLを使用したい絵を描くこと。これまでのところ、私が書いたコードは次のとおりです(これはmain.cpp
ファイルです。必要な場合はppm.hpp
、ppm.cpp
追加するように教えてください)
#include <iostream>
#include <SDL/SDL.h>
#include "ppm.hpp"
using namespace std;
void drawPixel (SDL_Surface*, Uint8, Uint8, Uint8, int, int);
int main (int argc, char** argv) {
PPM ppm ("res/cake.ppm");
if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO) < 0) {
cerr << "Unable to init SDL: " << SDL_GetError() << endl;
exit(1);
}
atexit(SDL_Quit); // to automatically call SDL_Quit() when the program terminates
SDL_Surface* screen;
screen = SDL_SetVideoMode(ppm.width(), ppm.height(), 32, SDL_SWSURFACE);
if (screen == nullptr) {
cerr << "Unable to set " << ppm.width() << "x" << ppm.height() << " video: " << SDL_GetError() << endl;
exit(1);
}
for (int i = 0; i < ppm.width(); i++) {
for(int j = 0; j < ppm.height(); j++) {
drawPixel(screen, ppm.red(i,j), ppm.green(i,j), ppm.blue(i,j), i, j);
}
}
return 0;
}
void drawPixel (SDL_Surface* screen, Uint8 R, Uint8 G, Uint8 B, int x, int y) {
Uint32 color = SDL_MapRGB(screen->format, R, G, B);
if (SDL_MUSTLOCK(screen)) {
if (SDL_LockSurface(screen) < 0) {
return;
}
}
switch (screen->format->BytesPerPixel) {
case 1: { // Assuming 8-bpp
Uint8* bufp;
bufp = (Uint8*)screen->pixels + y * screen->pitch + x;
*bufp = color;
}
break;
case 2: { // Probably 15-bpp or 16-bpp
Uint16 *bufp;
bufp = (Uint16*)screen->pixels + y * screen->pitch / 2 + x;
*bufp = color;
}
break;
case 3: { // Slow 24-bpp mode, usually not used
Uint8* bufp;
bufp = (Uint8*)screen->pixels + y * screen->pitch + x;
*(bufp + screen->format->Rshift / 8) = R;
*(bufp + screen->format->Gshift / 8) = G;
*(bufp + screen->format->Bshift / 8) = B;
}
break;
case 4: { // Probably 32-bpp
Uint32* bufp;
bufp = (Uint32*)screen->pixels + y * screen->pitch / 4 + x;
*bufp = color;
}
break;
}
if (SDL_MUSTLOCK(screen)) {
SDL_UnlockSurface(screen);
}
SDL_UpdateRect(screen, x, y, 1, 1);
}
これdrawPixel
はイントロダクションで提供されているとおりです。現在、使用しようとしている ppm ファイルが呼び出されcake.ppm
、その 720x540 ですが、このコードをビルドして実行すると、アプリケーションが応答しません。426x299 の小さな ppm ファイルで試してみたところ、ウィンドウに色が付けられたウィンドウが表示されました。
- ファイルで機能せず、他のファイルで機能するのはなぜ
cake.ppm
ですか? サイズによるのでは? - ppm ファイル、2 番目の 426x299 またはその他の ppm ファイルを試すと、色がまったく異なります。なぜですか?
- アプリを実行すると、ピクセルが配置された後、ウィンドウが閉じます。どうすればウィンドウを保持できますか?
filesquares.ppm
を試行すると、次のようになります。
しかし、これは私が得ているものです