SDL3 texture alpha blend not working

I searched the board for this and all the current solutions seem to only apply to SDL2. I am creating a SDL_Texture to use as a render target but I am trying to render it with a clear background. I was able to do this in SDL2 by setting a draw color of 0 and calling SDL_RenderClear() but it does not seem to work in SDL3.

Here is the code I am using:

SDL_SetTextureBlendMode(target, SDL_BLENDMODE_BLEND);
SDL_SetRenderTarget(renderer, target);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);

It seems to ignore the alpha value no matter what I do. Does anyone have a solution for this?

This should work, can you put together a minimal complete example that shows the problem?

Does this work on your system?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <SDL3/SDL.h>
#include <SDL3/SDL_main.h>

static const int WINDOW_WIDTH = 800;
static const int WINDOW_HEIGHT = 600;

static void bailout(const char *title, const char *message)
{
	fprintf(stderr, "ERROR: %s: %s\n", title, message);
	SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, title, message, NULL);
	exit(EXIT_FAILURE);
}

int main(int argc, char *argv[])
{
	if(!SDL_Init(SDL_INIT_VIDEO)) {
		bailout("Can't Init SDL", SDL_GetError());
	}

	atexit(SDL_Quit);

	uint32_t windowFlags = 0;
	SDL_Window *window = SDL_CreateWindow("SDL3 Render Target Alpha Blending",
			WINDOW_WIDTH, WINDOW_HEIGHT, windowFlags);
	if(window == NULL) {
		bailout("Can't Create Window", SDL_GetError());
	}

	SDL_Renderer *renderer = SDL_CreateRenderer(window, NULL);
	if(renderer == NULL) {
		bailout("Can't Create Renderer", NULL);
	}

	SDL_Texture *targetTex = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32,
			SDL_TEXTUREACCESS_TARGET, WINDOW_WIDTH, WINDOW_HEIGHT);
	if(targetTex == NULL) {
		bailout("Can't Create Render Target", SDL_GetError());
	}

	int quit = 0;
	while(!quit) {
		SDL_Event event;
		while(SDL_PollEvent(&event)) {
			switch(event.type) {
			case SDL_EVENT_QUIT:
				quit = 1;
				break;
			}
		}

		SDL_SetRenderTarget(renderer, targetTex);
		SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
		SDL_RenderClear(renderer);

		SDL_FRect drawRect = { 50.0f, 50.0f, 200.0f, 200.0f };

		SDL_SetRenderDrawColor(renderer, 255, 0, 0, 127);
		SDL_RenderFillRect(renderer, &drawRect);
		SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
		SDL_RenderRect(renderer, &drawRect);

		SDL_SetRenderTarget(renderer, NULL);
		SDL_SetRenderDrawColor(renderer, 0, 127, 255, 255);
		SDL_RenderClear(renderer);

		SDL_RenderTexture(renderer, targetTex, NULL, NULL);

		SDL_RenderPresent(renderer);
	}

	return 0;
}

On my system it works correctly:

1 Like

Thanks for this example. It helped me with my issue.

My issue was that I was using SDL_GetWindowPixelFormat() to set the texture pixel format to the pixel format of the window which probably didn’t support alpha blending. I manually set the pixel format like you did in your example and it worked.