wxPython - GC.DrawText 删除背景位图

wxPython - GC.DrawText removes background bitmap

我试图在现有位图上绘制文本,但是当我使用 Graphics Context 的 DrawText 方法时,背景被删除了。但这仅在我从空位图创建背景图像时发生(在加载图像的位图上使用 DrawText 效果很好)。 我认为这个问题的发生是因为我使用 MemoryDC 创建一个空位图,但我对 wxPython 很陌生,所以我不知道如何修复它。

这是我目前所做的:

import wx

def GetEmptyBitmap(w, h, color=(0,0,0)):
    """
    Create monochromatic bitmap with desired background color.
    Default is black
    """
    b = wx.EmptyBitmap(w, h)
    dc = wx.MemoryDC(b)
    dc.SetBrush(wx.Brush(color))
    dc.DrawRectangle(0, 0, w, h)
    return b

def drawTextOverBitmap(bitmap, text='', fontcolor=(255, 255, 255)):
    """
    Places text on the center of bitmap and returns modified bitmap.
    Fontcolor can be set as well (white default)
    """
    dc = wx.MemoryDC(bitmap)
    gc = wx.GraphicsContext.Create(dc)
    font = wx.Font(16, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
    gc.SetFont(font, fontcolor)
    w,h = dc.GetSize()
    tw, th = dc.GetTextExtent(text)    
    gc.DrawText(text, (w - tw) / 2, (h - th) / 2)
    return bitmap

app = wx.App()
bmp_from_img =  bmp = wx.Image(location).Rescale(200, 100).ConvertToBitmap()
bmp_from_img = drawTextOverBitmap(bmp_from_img, "From Image", (255,255,255))

bmp_from_empty =  GetEmptyBitmap(200, 100, (255,0,0))
bmp_from_empty = drawTextOverBitmap(bmp_from_empty, "From Empty", (255,255,255))


frame = wx.Frame(None)
st1 = wx.StaticBitmap(frame, -1, bmp_from_img, (0,0), (200,100))
st2 = wx.StaticBitmap(frame, -1, bmp_from_empty, (0, 100), (200, 100))
frame.Show()
app.MainLoop()

正如我所说,使用加载图像的 StaticBitmap 显示正确,但使用 EmptyBitmap 创建的没有背景。

你有什么想法让它发挥作用吗?

谢谢

这对我来说似乎是一个错误。使用以下命令使其工作:

def GetEmptyBitmap(w, h, color=(0,0,0)):
    # ...
    # instead of
    # b = wx.EmptyBitmap(w, h)
    # use the following:
    img = wx.EmptyImage(w, h)
    b = img.ConvertFromBitmap()
    # ...

我认为这不是 wx.MemoryDC 的罪魁祸首,而是平台特定的位图创建例程,其中隐藏着更多内容。从 wx.Image 开始,输出似乎更多 predictable/useful.