wx.SetTextForeground 没有在 wxPython 中正确设置 DC 颜色

wx.SetTextForeground doesn't set DC color properly in wxPython

我有以下代码,我正在尝试更改 DC 的文本颜色。我在网上搜索了一下,发现 SetTextForeground 应该用于此目的,但不知何故我无法让它工作。

import wx

class GUI():        
    def __init__(self):
        self.InitUI()

    def InitUI(self):
        self.window  = wx.Frame(None, wx.ID_ANY, "Example Title")

        textList = ['text1', 'text2']
        for i in range(len(textList)):
            bmp = wx.Image('images/step_background.png').Rescale(160, 40).ConvertToBitmap()
            bmp = self.drawTextOverBitmap(bmp, textList[i])
            control = wx.StaticBitmap(self.window, -1, bmp, (0, 30*i+20), size=(160,30))
        self.window.Show()


    def drawTextOverBitmap(self, bitmap, text='', color=(0, 0, 0)):
            dc = wx.MemoryDC(bitmap)
            dc.SetTextForeground(color)
            w,h = dc.GetSize()
            tw, th = dc.GetTextExtent(text)
            dc.DrawText(text, (w - tw) / 2, (h - th) / 2) #display text in center
            return bitmap

if __name__ == '__main__':
    app = wx.App()
    gui = GUI()
    app.MainLoop()

你知道我做错了什么吗?如果有任何想法,我将不胜感激。

谢谢

你是对的,透明度是这里的问题。在非透明图像上尝试了您的代码,它可以正常显示您设置的颜色。

引用自official docs

In general wxDC methods don't support alpha transparency and the alpha component of wxColour is simply ignored and you need to use wxGraphicsContext for full transparency support.

因此尝试创建一个图形上下文,例如:

        dc = wx.MemoryDC(bmp)
        gc = wx.GraphicsContext.Create(dc)
        font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        gc.SetFont(font, "Red")
        w,h = dc.GetSize()
        tw, th = dc.GetTextExtent(textList[i])
        gc.DrawText(textList[i], (w - tw) / 2, (h - th) / 2)