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

标签 python wxwidgets

我有以下代码,我正在尝试更改 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)

关于python - wx.SetTextForeground 没有在 wxPython 中正确设置 DC 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36132230/

相关文章:

c++ - wxWidget v2.8 软件。让它与 3.0 库一起使用?

python - 设置wx.Frame大小(wxPython - wxWidgets)

python - 使用 BeautifulSoup 提取数据

python - Matplotlib 轴标签不显示

user-interface - 是否可以在 wxwidgets 中确定窗口当前是否可见?

c++ - 使用参数从 cmd.exe 执行 MSYS

c++ - 在 wxWidgets 的事件中包含我自己的数据的最佳方式是什么?

python - 如何在 Windows 上的 python 中安装 METIS 包?

python - 关于 python web 的最佳持续更新资源 "plumbing"

python - 如何通过 DataFrame 压扁 Pandas group?