如何在顶层绘制矩形

时间:2014-01-07 07:34:57

标签: python wxpython

我想通过鼠标移动在位图顶部绘制一个矩形。但矩形是在位图下呈现的。以下是我的代码。

#!/usr/bin/env python

import sys, os
import wx
import wx.lib.scrolledpanel as scrolled

class ImgPanel(scrolled.ScrolledPanel):
    def __init__(self, parent):
        super(ImgPanel, self).__init__(parent, 
                                       style = wx.SUNKEN_BORDER)

        self.bitmap=wx.StaticBitmap(parent=self)
        image = wx.Bitmap('image.jpg')
        self.bitmap.SetBitmap(image)

        self.imgSizer = wx.BoxSizer(wx.VERTICAL)        
        self.imgSizer.Add(self.bitmap, 1, wx.EXPAND)
        self.SetSizer(self.imgSizer)

        self.SetAutoLayout(1)
        self.SetupScrolling()    
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.bitmap.Bind(wx.EVT_MOTION, self.OnMove)
        self.bitmap.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.bitmap.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.IsRectReady = False
        self.newRectPara=[0,0,0,0]


    def OnMove(self,evt):
        if True == self.IsRectReady:
            self.newRectPara[2]=evt.GetPosition()[0]-self.newRectPara[0]+1
            self.newRectPara[3]=evt.GetPosition()[1]-self.newRectPara[1]+1
            self.Refresh()

    def OnLeftDown(self, evt):
        self.IsRectReady=True
        self.newRectPara[0]=evt.GetPosition()[0]
        self.newRectPara[1]=evt.GetPosition()[1]


    def OnLeftUp(self, evt):
        self.IsRectReady=False

    def OnPaint(self, evt):        
        dc=wx.PaintDC(self)
        dc.Clear()
        if self.IsRectReady:
            dc.DrawRectangle(self.newRectPara[0], self.newRectPara[1],
                             self.newRectPara[2], self.newRectPara[3])

class  WinFrame(wx.Frame):
    def __init__(self, parent, title, width, height):
        super(WinFrame, self).__init__(parent, 
                                       title=title,
                                       size=(width, height))

        self.imgPanel = ImgPanel(self)
        self.frameSizer = wx.BoxSizer(wx.HORIZONTAL)        
        self.frameSizer.Add(self.imgPanel, 1, wx.EXPAND)        
        self.SetAutoLayout(True)
        self.SetSizer(self.frameSizer)
        self.Layout()      

        self.Centre()
        self.Show(True)        


class MyApp(wx.App):
    def __init__(self, width, height):
        super(MyApp, self).__init__(0)

        self.width = width
        self.height = height

    def createFrame(self):
        self.frame = WinFrame(None, "test", self.width, self.height)
        self.SetTopWindow(self.frame)    

def main():
    app = MyApp(640, 480)
    app.createFrame()
    app.MainLoop()

if "__main__" == __name__ :
    main()

1 个答案:

答案 0 :(得分:2)

由于wx.StaticBitmap是一个单独的(子)窗口,因此它始终位于其父窗口ImgPanel之上。换句话说,在ImgPanel上完成的任何绘图将始终位于位图小部件的后面或下面。如果您想要合并图像和图形,那么您应该将位图添加到EVT_PAINT处理程序中,而不是使用wx.StaticBitmap。