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

问题描述 投票:1回答:1

这是我绘制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;
}

虽然我可以画rectSDL_Renderer对象renderer就好了,如果我添加rect2它总是不透明,阻挡rect的视图。即使我将rect2的alpha设置为0,它仍然显示不透明,阻止rect从视图。

我如何解决这个问题,让rect2更透明?

c++ sdl render sdl-2 rect
1个回答
3
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.