wxpython在StaticBitmap上绘图

jac*_*boy 4 python wxpython

嘿,我试图在用户单击图形上的某个点时在图像顶部绘制一个矩形。

要滚动浏览不同的图形,我使用了staticBitmap。不幸的是,几乎所有与DC的尝试都没有成功。PaintDC和BufferedDC有时会导致无限循环发生,而其他时候则将图形置​​于图像后面。ClientDC会显示我绘制的框,但是当我调整尺寸时它会消失。当我仅将图像保存到文件中但无法放置在staticBitmap中时,可以使用MemoryDC创建图形。

我花了大约一个星期的时间来解决这个问题,阅读了很多不同的教程和论坛来尝试找到同样的问题。我觉得没有其他人遇到这个问题。

每当调整窗口大小时,最重用的ClientDC必须重新绘制,从而导致闪烁。这是ClientDC的功能:

    self.imageCtrl = wx.StaticBitmap(self.thePanel, wx.ID_ANY, 
                                     wx.EmptyBitmap(517,524))

def OnGoSelect(self,e):
    print "GO"
    img = wx.Image("./poster/"+self.picChoice,wx.BITMAP_TYPE_PNG) 
    self.imageCtrl.SetBitmap(wx.BitmapFromImage(img))

def DrawLine(self):
    dc = wx.ClientDC(self.imageCtrl)
    dc.SetPen(wx.Pen(wx.BLUE, 2))
    dc.DrawLines(((223, 376), (223, 39), (240, 39), (240,376), (223,376)))
Run Code Online (Sandbox Code Playgroud)

当前的PaintDC不会进入无限循环,而是将图像放置在staticBitmap中,并且绘图以某种方式位于图像的后面。因此,当我调整大小时,ComboBoxes会擦除图像的一部分并调整窗口大小以覆盖图像,从而擦除该部分。当我调整窗口的大小时,图形仍然存在,但是图像被删除了。这是我所拥有的:

    self.imageCtrl = wx.StaticBitmap(self.thePanel, wx.ID_ANY, 
                                     wx.EmptyBitmap(517,524))

def OnGoSelect(self,e):
    print "GO"
    img = wx.Image("./poster/"+self.picChoice,wx.BITMAP_TYPE_PNG) 
    self.imageCtrl.SetBitmap(wx.BitmapFromImage(img))

    self.imageCtrl.Bind(wx.EVT_PAINT, self.OnPaint)

def OnPaint(self, e):
    print "OnPaint Triggered"
    dc = wx.PaintDC(self.imageCtrl)
    dc.Clear()
    dc.SetPen(wx.RED_PEN)
    dc.DrawLines(((100, 200), (100, 100), (200, 100), (200,200), (100,200))) 
Run Code Online (Sandbox Code Playgroud)

对于MemoryDC,我自己全部加载了EmptyBitmap,在其上绘制,然后尝试将其放入staticBitmap中。它给了我空白的灰色屏幕。如果我没有在EmptyBitmap上绘图,它会正常显示为黑色。即使在使用它时,我仍将其保存到文件中,该文件应以应有的方式出现,但仍使应用程序内部出现灰屏。这是MemoryDC代码:

    self.imageCtrl = wx.StaticBitmap(self.thePanel, wx.ID_ANY, 
                                     wx.EmptyBitmap(517,524))

def Draw(self, e):
    print "Draw" 
    img = wx.Image("./poster/Test2.png", wx.BITMAP_TYPE_ANY)
    bit = wx.EmptyBitmap(517,524)
    dc = wx.MemoryDC(bit)
    dc.SetBackground(wx.Brush(wx.BLACK))
    dc.Clear()
    dc.SetPen(wx.Pen(wx.RED, 1))
    dc.DrawLines(((83, 375), (83, 42), (120, 42), (120,375), (83,375)))
    self.imageCtrl.SetBitmap(bit)  
    bit.SaveFile("bit.bmp", wx.BITMAP_TYPE_BMP)
Run Code Online (Sandbox Code Playgroud)

我机智。欢迎任何建议!

jac*_*boy 5

我找到了!

我之前不知道在使用MemoryDC时必须取消选择要绘制到的位图。这是通过将wx.NullBitmap传递给SelectObject方法来完成的。

这是MemoryDC的代码:

def Draw(self, e):
    print "Draw" 
    img = wx.Image("./poster/Test2.png", wx.BITMAP_TYPE_ANY)
    bit = wx.EmptyBitmap(517,524)
    imgBit = wx.BitmapFromImage(img)
    dc = wx.MemoryDC(imgBit)
    dc.SetPen(wx.Pen(wx.RED, 1))
    dc.DrawLines(((83, 375), (83, 42), (120, 42), (120,375), (83,375)))
    dc.SelectObject(wx.NullBitmap)# I didn't know I had to deselect the DC
    self.imageCtrl.SetBitmap(imgBit)  
    imgBit.SaveFile("bit.bmp", wx.BITMAP_TYPE_BMP)
Run Code Online (Sandbox Code Playgroud)