SDL将像素放在屏幕上C ++

时间:2013-04-07 20:36:19

标签: c++ sdl pixel ppm

我从SDL开始,我正在阅读介绍,我正在尝试他们拥有的drawPixel方法。我正在做的是一个ppm查看器,到目前为止,我有一个数组中的rgb值并正确存储(我通过打印数组检查它们并确保它们对应于它们在ppm文件中的位置)并且我想使用SDL绘制图片。到目前为止,我编写的代码是(这是main.cpp文件,如果需要ppm.hppppm.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,但是当我构建并运行此代码时,我得到了应用程序没有回应。我在一个较小的ppm文件(426x299)上尝试了它,它显示了一个窗口,颜色放在窗口上。

  1. 为什么它不在cake.ppm文件上工作,而在其他文件上工作呢?是因为尺寸?
  2. 当我尝试ppm文件,第二个426x299或其他ppm文件时,颜色完全不同,为什么会这样?
  3. 当我运行应用程序时,在放置像素后,窗口关闭,我该如何保留它?
  4. 尝试文件squares.ppm,这应该是: what it should be

    但这就是我所得到的 what I'm getting

0 个答案:

没有答案