TrueTypeFont#render output doesn't obey alpha

  • I want to render a bit of text and then blit it to my display surface with alpha enabled, but when I do that it doesn't seem to work.

    My display surface is 1024x768x24 (but also tried at x32):

    text = @font.render( @letters[i], true, @color )
    if @letter_counts[ @letters[ i ] ] == 0
    # This doesn't work when antialiasing..
    text.set_alpha 128
    surface.blit( text, @x, @y )

    When I take off the antialias flag, I get an 8 bit surface and the alpha works, otherwise it returns 32 bit and the alpha is ignored. When I call Surface#convert it turns my font into a solid block (illegible). When I call convert_alpha, nothing visibly happens (still no alpha). This is true of the bang! methods as well.

    Am I missing something obvious?

    Thanks in advance for any advice you can give.


    • Renne Nissinen
      Renne Nissinen

      The problem is that SDL doesn't support per-pixel alpha at the same time as per-surface alpha. I can think of two solutions: either use a font that doesn't need antialiasing to look good, or do the following trick:

      1. render the text with antialiasing
      2. copy the part of the screen surface where you're going to draw the text, into a new surface
      3. blit the text on top of this copy
      4. set_alpha on this copy, and blit it back to the screen

      • Thanks for that tip. I managed to get around it, but it sounds like a good workaround that will be helpful in the future.

        My current boggle is somewhat related to this though - I've had some difficulties copying parts of the screen as you suggest. Is there a better way of copy part of a surface or an entire surface than just making a new surface and blitting to it? I've had some weird problems with losing alpha etc.

        For example, I have a PNG with an alpha channel, but using the create and blit method I seem to lose the background alpha. Also, setting surface1.pixels=surface2.pixels doesn't seem to do the trick even with the same surface flags and bit depths. When trying to make an exact copy of a loaded surface, Surface#clone and Surface#dup seem to cause errors.

        So is there a good way of:

        a) Copying a section of a surface into a new surface? Sorry - I couldn't find an easy way of doing this so far besides new surface + blit.

        b) Duplicating / deep copying another surface while preserving any weird PNG alpha channel stuff?

        Thanks again for your tip and in advance for any additional advice you can give me here.