【发布时间】:2017-11-15 08:32:40
【问题描述】:
我的代码引发访问错误。这是代码:
SDL_Color *getPixelColor(SDL_Surface *loadingSurface, int x, int y) {
SDL_Color getColor = {0,0,0};
SDL_Texture *readingTexture = nullptr;
readingTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, loadingSurface->w, loadingSurface->h);
SDL_SetTextureBlendMode(readingTexture, SDL_BLENDMODE_BLEND);
void * vPixels;
SDL_LockTexture(readingTexture, &loadingSurface->clip_rect, &vPixels, &loadingSurface->pitch);
memcpy(vPixels, loadingSurface->pixels, loadingSurface->w * loadingSurface->h);
Uint32 *aPixels = (Uint32*)vPixels;
SDL_UnlockTexture(readingTexture);
//Get pixel at location.
Uint32 getPixel = aPixels[y * loadingSurface->w + x];
Uint8 *colors = (Uint8*)getPixel;
//cout << colors[0] << " " << colors[1] << " " << colors[2] << endl;
getColor.r = colors[0];
getColor.g = colors[1];
getColor.b = colors[2];
SDL_Color *color = &getColor;
return color;
}
抛出异常:读取访问冲突。 颜色为 0xFF00。
任何时候我都会尝试访问颜色。 SDL 文档中描述的方法都返回相同的错误,并且互联网上除了 LazyFoo 之外没有任何信息(此方法基于该方法,但它不起作用。)
感谢您的帮助。
编辑:
我通过重新编写代码来修复我的代码,并忽略了一些我用来理解 SDL 某些部分的错误来源。这是工作代码:
Uint32 getPixel(SDL_Surface *loadingSurface, int x, int y) {
Uint32 *pixels = (Uint32*)loadingSurface->pixels;
return pixels[(y * loadingSurface->pitch / 4) + x]; // I noticed that each y selection was off by 4 pixels in the y so I divided by 4. Why this is the case remains a mystery.
}
为什么我需要除以 4 是个谜,我花了一段时间才弄明白。任何想法为什么?
SDL_Color getPixelColor(SDL_Surface *loadingSurface, int x, int y) {
SDL_Color getColor = {0,0,0};
SDL_PixelFormat *format;
Uint32 pixel, index;
Uint8 red, green, blue, alpha;
format = loadingSurface->format;
SDL_LockSurface(loadingSurface);
pixel = getPixel(loadingSurface, x, y);
SDL_UnlockSurface(loadingSurface);
index = pixel & format->Rmask;
index = index >> format->Rshift;
index = index << format->Rloss;
red = (Uint8)index;
index = pixel & format->Gmask;
index = index >> format->Gshift;
index = index << format->Gloss;
green = (Uint8)index;
index = pixel & format->Bmask;
index = index >> format->Bshift;
index = index << format->Bloss;
blue = (Uint8)index;
index = pixel & format->Amask;
index = index >> format->Ashift;
index = index << format->Aloss;
alpha = (Uint8)index;
getColor.r = red;
getColor.g = green;
getColor.b = blue;
getColor.a = alpha;
return getColor;
}
【问题讨论】: