我试图在现有位图上绘制文本,但是当我使用图形上下文的 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 创建的 StaticBitmap 没有背景。
你有什么想法让它发挥作用吗?
谢谢
最佳答案
这对我来说似乎是一个错误。使用以下命令使其工作:
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
开始,输出似乎更可预测/更有用。
关于python - wxPython - GC.DrawText 删除背景位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36447192/