如何在SDL2中的不透明矩形上绘制透明或半透明矩形?

时间:2016-02-14 22:05:25

标签: c++ sdl render sdl-2 rect

这是我绘制SDL_Rect个对象rectrect2的代码:

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

int main(){
    SDL_Window *window=     SDL_CreateWindow("Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN);
    if(window == 0)
        std::cout << SDL_GetError() << std::endl;

    SDL_Renderer *renderer= SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if(renderer == NULL)
        std::cout << SDL_GetError() << std::endl;

    SDL_Rect rect;
    rect.x=     100;
    rect.y=     100;
    rect.w=     100;
    rect.h=     100;

    SDL_Rect rect2;
    rect2.x=    150;
    rect2.y=    150;
    rect2.w=    100;
    rect2.h=    100;

    while(true){
        Uint8 r,g,b,a;

        r=  32;
        g=  32;
        b=  32;
        a=  255;
        if(SDL_SetRenderDrawColor(renderer, r, g, b, a) == -1)
            std::cout << SDL_GetError() << std::endl;
        if(SDL_RenderClear(renderer) == -1)
            std::cout << SDL_GetError() << std::endl;

        r=  255;
        g=  255;
        b=  255;
        a=  255;
        if(SDL_SetRenderDrawColor(renderer, r, g, b, a) == -1)
            std::cout << SDL_GetError() << std::endl;
        if(SDL_RenderFillRect(renderer, &rect) == -1)
            std::cout << SDL_GetError() << std::endl;

        r=  100;
        g=  100;
        b=  100;
        a=  0;
        if(SDL_SetRenderDrawColor(renderer, r, g, b, a) == -1)
            std::cout << SDL_GetError() << std::endl;
        if(SDL_RenderFillRect(renderer, &rect2) == -1)
            std::cout << SDL_GetError() << std::endl;

        SDL_RenderPresent(renderer);
    }

    return 0;
}

虽然我可以将rect绘制到SDL_Renderer对象renderer,但如果我添加rect2,则它始终是不透明的,阻止了rect的视图。即使我将rect2的alpha设置为0,它仍会显示不透明,阻止rect从视图中显示。

如何解决此问题,以便rect2更透明?

1 个答案:

答案 0 :(得分:3)

您需要做的就是致电 SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
创建渲染器后,使用RenderDraw函数启用Alpha混合。 (SDL documentation