【发布时间】:2016-04-06 09:38:17
【问题描述】:
我正在尝试在现有位图上绘制文本,但是当我使用 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 创建的静态位图没有背景。
你有什么想法可以让它发挥作用吗?
谢谢
【问题讨论】:
标签: python bitmap background wxpython