1
我試圖在現有的位圖上繪製文本,但是當我使用圖形上下文的DrawText方法時,背景被刪除。但是,只有當我從空位圖創建背景圖像時(使用加載圖像的位圖上的DrawText運行良好)纔會發生這種情況。 我認爲這個問題是因爲我使用MemoryDC來創建一個空位圖,但我對wxPython很陌生,所以我不知道如何解決它。wxPython - GC.DrawText刪除背景位圖
這是我到目前爲止已經完成:
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()
正如我所說的,它使用加載的圖像顯示正確,但EmptyBitmap創建一個沒有背景的StaticBitmap。
你有什麼想法如何使它工作?
謝謝
謝謝,這實際上解決了這個問題。 雖然我一直在尋找解決方案,但我被告知這可能是由於默認爲0而導致的。 –
我無法證明它必須用alpha來做某件事,但它似乎確實是問題所在。嘗試以下方法:''b = wx.EmptyBitmapRGBA(w,h,* color,alpha = 255)'',''img = b.ConvertToImage()'',''b = img.ConvertToBitmap()''。通過'wx.Image'來回轉儲Alpha通道,然後工作。 – nepix32
[Tim Roberts on google groups wxPython-users](https://groups.google.com/forum/#!topic/wxpython-users/huyH0pKklks)找到了同樣的東西:讓位圖沒有alpha通道使得ting工作。 – nepix32