def refresh(self):
dc = wx.MemoryDC(self.drawingBuffer)
dc.SelectObject(self.drawingBuffer)
dc.SetBackground(wx.Brush(self.background, style=wx.SOLID))
dc.Clear()
gc = wx.GraphicsContext.Create(dc)
# do not draw if window is very small, right solution? XXX - idfah
if self.winRadius < 1.0e-3:
return
self.draw(gc)
dc.SelectObject(wx.NullBitmap)
self.triggerRepaint()
python类MemoryDC()的实例源码
def _drawPointLabel(self, mDataDict):
"""Draws and erases pointLabels"""
width = self._Buffer.GetWidth()
height = self._Buffer.GetHeight()
if sys.platform != "darwin":
tmp_Buffer = wx.Bitmap(width, height)
dcs = wx.MemoryDC()
dcs.SelectObject(tmp_Buffer)
dcs.Clear()
else:
tmp_Buffer = self._Buffer.GetSubBitmap((0, 0, width, height))
dcs = wx.MemoryDC(self._Buffer)
self._pointLabelFunc(dcs, mDataDict) # custom user pointLabel function
dc = wx.ClientDC(self.canvas)
dc = wx.BufferedDC(dc, self._Buffer)
# this will erase if called twice
dc.Blit(0, 0, width, height, dcs, 0, 0, self._logicalFunction)
if sys.platform == "darwin":
self._Buffer = tmp_Buffer
def DrawFromSelectedNode(self, msg):
t = msg.replace("][", ",").replace("[", "").replace("]", "").split(",")
osx = int(t[0])
osy = int(t[1])
oex = int(t[2])
oey = int(t[3])
i = wx.Bitmap(os.path.join(self.screenShotDir, "screenshot.png"))
dc = wx.MemoryDC(i)
dc.SetPen(wx.Pen(wx.RED, 1))
#???(wxpython????drawline?drawlines, ??drawrect??????)
dc.DrawLine(osx, osy, osx, oey)
dc.DrawLine(osx, osy, oex, osy)
dc.DrawLine(oex, osy, oex, oey)
dc.DrawLine(osx, oey, oex, oey)
dc.SelectObject(wx.NullBitmap)
self.screenShot.SetBitmap(i)
self.Refresh(eraseBackground=True, rect=None)
def DisplayImage(self):
if self.current_image:
tw = self.static_bitmap.GetSize().GetWidth()
th = self.static_bitmap.GetSize().GetHeight()
sw = self.current_image.GetSize().GetWidth()
sh = self.current_image.GetSize().GetHeight()
#self.scale = min(tw/float(sw),th/float(sh))
tw = int(sw*self.scale)
th = int(sh*self.scale)
im = self.current_image.Copy()
im.Rescale(tw,th)
bm = im.ConvertToBitmap()
bmdc = wx.MemoryDC(bm)
bmdc.SetBrush(wx.TRANSPARENT_BRUSH)
bmdc.SetPen(wx.RED_PEN)
bmdc.SetTextForeground(wx.RED)
i = 1
for point in self.coords[self.image_name]:
bmdc.DrawCircle(self.scale*point[0], self.scale*point[1], 5)
w,h = bmdc.GetTextExtent(str(i))
bmdc.DrawText(str(i),self.scale*point[0]-w/2, self.scale*point[1]+5)
i += 1
del bmdc
self.static_bitmap.SetBitmap(bm)
# ------------- Event Handlers ---------------
def OnLeftRelease(self,e):
self.player.stop()
self.brec.SetBitmapLabel(self.brecxicon)
self.bplay.SetBitmapLabel(self.bplayicon)
if self.hasSelected:
#the frame selected was clicked
img = self.MakeThumbnail(os.path.join(self.imgdir, self.selected.GetName() ), self.thumbsize)
self.selected.SetBitmap(wx.BitmapFromImage(img) )
self.hasSelected = True
self.previous = 0
self.player.play()
self.viewport.Refresh()
self.brec.SetBitmapLabel(self.brecicon)
if not self.hasSelected:
# we clicked something new
# get new selection
self.selected = e.GetEventObject()
# highlight new selection
img = self.MakeThumbnail(os.path.join(self.imgdir, self.selected.GetName() ), self.thumbsize + 3)
imgb = wx.BitmapFromImage(img)
dc = wx.MemoryDC(imgb)
staricon = wx.Image(os.path.join(os.path.dirname(__file__),'..','..','stopgo','images','select.png') )
star = wx.BitmapFromImage(staricon)
dc.DrawBitmap(star,133,0)
dc.SelectObject(wx.NullBitmap)
del dc
control = wx.StaticBitmap(self, -1, imgb)
self.selected.SetBitmap(imgb)
self.hasSelected = True
self.previous = self.selected.GetId()
#paint canvas
img = self.MakeThumbnail(os.path.join( self.imgdir, self.selected.GetName() ), self.screenHeight*.9)
self.GetStatusBar().SetStatusText(self.selected.GetName(), 0)
self.PaintCanvas(img)
self.viewport.Refresh()
def refresh(self):
"""Refresh the drawing area after a change has been made.
This method sets up a drawing context, calls self.draw
to update the drawing and then calls self.triggerRepaint
in order to update the drawing area on the screen.
This method should be called each time a change is
made that requires the drawing area to be updated.
"""
dc = wx.MemoryDC(self.drawingBuffer)
dc.SelectObject(self.drawingBuffer)
dc.SetBackground(wx.Brush(self.background, style=wx.SOLID))
dc.Clear()
# do not draw if window is very small, right solution? XXX - idfah
if self.winRadius < 1.0e-3:
return
#dc.BeginDrawing()
self.draw(dc)
#dc.EndDrawing()
#del dc
dc.SelectObject(wx.NullBitmap)
self.triggerRepaint()
def DrawROI(self):
object = self.object
bmp = self.image.GetBitmap()
w = bmp.GetWidth()
h = bmp.GetHeight()
roi = [0]*6
for i in range(3):
roi[2*i] = int(self.roi[2*i].value.GetValue()) - 1
roi[2*i+1] = int(self.roi[2*i+1].value.GetValue())
axis = int(self.scrollaxis.value.GetValue())
if axis == 1:
x1 = int(float(w*roi[4])/float(object.shape[2]) +0.5)
x2 = int(float(w*(roi[5]))/float(object.shape[2]) -0.5)
y1 = int(float(h*roi[2])/float(object.shape[1]) +0.5)
y2 = int(float(h*(roi[3]))/float(object.shape[1]) -0.5)
elif axis == 2:
x1 = int(float(w*roi[4])/float(object.shape[2]) +0.5)
x2 = int(float(w*(roi[5]))/float(object.shape[2]) -0.5)
y1 = int(float(h*roi[0])/float(object.shape[0]) +0.5)
y2 = int(float(h*(roi[1]))/float(object.shape[0]) -0.5)
elif axis == 3:
x1 = int(float(w*roi[2])/float(object.shape[1]) +0.5)
x2 = int(float(w*(roi[3]))/float(object.shape[1]) -0.5)
y1 = int(float(h*roi[0])/float(object.shape[0]) +0.5)
y2 = int(float(h*(roi[1]))/float(object.shape[0]) -0.5)
self.dc = wx.MemoryDC(bmp)
self.dc.SelectObject(bmp)
self.dc.SetPen(wx.Pen(wx.RED, 1))
self.dc.SetBrush(wx.TRANSPARENT_BRUSH)
self.dc.DrawLine(x1, 1, x1, h)
self.dc.DrawLine(x2, 1, x2, h)
self.dc.DrawLine(1, y1, w, y1)
self.dc.DrawLine(1, y2, w, y2)
self.dc.SelectObject(wx.NullBitmap)
self.image.SetBitmap(bmp)
self.Layout()
def DrawROI(self):
object = self.object
bmp = self.image.GetBitmap()
w = bmp.GetWidth()
h = bmp.GetHeight()
roi = [0]*6
for i in range(3):
roi[2*i] = int(self.roi[2*i].value.GetValue()) - 1
roi[2*i+1] = int(self.roi[2*i+1].value.GetValue()) - 1
axis = int(self.scrollaxis.value.GetValue())
if axis == 1:
rx = int(float(w*roi[4])/float(object.shape[2]) +0.5)
rw = int(float(w*(roi[5] - roi[4] +1.0))/float(object.shape[2]) +0.5)
ry = int(float(h*roi[2])/float(object.shape[1]) +0.5)
rh = int(float(h*(roi[3] - roi[2] +1.0))/float(object.shape[1]) +0.5)
elif axis == 2:
rx = int(float(w*roi[4])/float(object.shape[2]) +0.5)
rw = int(float(w*(roi[5] - roi[4] +1.0))/float(object.shape[2]) +0.5)
ry = int(float(h*roi[0])/float(object.shape[0]) +0.5)
rh = int(float(h*(roi[1] - roi[0] +1.0))/float(object.shape[0]) +0.5)
elif axis == 3:
rx = int(float(w*roi[2])/float(object.shape[1]) +0.5)
rw = int(float(w*(roi[3] - roi[2] +1.0))/float(object.shape[1]) +0.5)
ry = int(float(h*roi[0])/float(object.shape[0]) +0.5)
rh = int(float(h*(roi[1] - roi[0] +1.0))/float(object.shape[0]) +0.5)
self.dc = wx.MemoryDC(bmp)
self.dc.SelectObject(bmp)
self.dc.SetPen(wx.Pen(wx.RED, 1))
self.dc.SetBrush(wx.TRANSPARENT_BRUSH)
self.dc.DrawRectangle(rx, ry, rw, rh)
self.dc.SelectObject(wx.NullBitmap)
self.image.SetBitmap(bmp)
self.Layout()
def clearScreenShot(self, bmp):
dc = wx.MemoryDC()
dc.SelectObject(bmp)
dc.SetBackground(wx.Brush("white"))
dc.Clear()
def draw_box(self):
x1, x2 = self.plot._point2ClientCoord(*self.selected)[::2]
dc = wx.ClientDC(self.plot.canvas)
dc.SetLogicalFunction(wx.INVERT)
dc.DrawRectangle(x1, 0, x2, dc.GetSize()[1])
dc.SetLogicalFunction(wx.COPY)
# def clear(self):
# # An experimental way to clear the canvas without redrawing the plot every time
# # dc.Blit() usage from SOF.
# if self.selection_drawn:
# self.draw_box() # clear old
# self.selection_drawn = False
# dc = wx.ClientDC(self.plot.canvas)
# size = dc.GetSize()
# bmp = wx.Bitmap(size.width, size.height)
# prev_dc = wx.MemoryDC()
# prev_dc.SelectObject(bmp)
# prev_dc.Blit(
# 0, # Copy to this X coordinate
# 0, # Copy to this Y coordinate
# size.width, # Copy this width
# size.height, # Copy this height
# dc, # From where do we copy?
# 0, # What's the X offset in the original DC?
# 0 # What's the Y offset in the original DC?
# )
# prev_dc.SelectObject(wx.NullBitmap)
# dc.Clear()
# dc.DrawBitmap(bmp, 0, 0)
# # if self.plot.last_draw is not None:
# # self.plot.Draw(self.plot.last_draw[0])
def GetLogicalDC(self, buffered=False):
if buffered:
bitmap = wx.EmptyBitmap(*self.Editor.GetClientSize())
dc = wx.MemoryDC(bitmap)
else:
dc = wx.ClientDC(self.Editor)
dc.SetFont(self.GetFont())
if wx.VERSION >= (2, 6, 0):
self.Editor.DoPrepareDC(dc)
else:
self.Editor.PrepareDC(dc)
dc.SetUserScale(self.ViewScale[0], self.ViewScale[1])
return dc
def GetBitmap(bmp_name1, bmp_name2=None, size=None):
bmp = BitmapLibrary.get((bmp_name1, bmp_name2, size))
if bmp is not None:
return bmp
if bmp_name2 is None:
bmp = SearchBitmap(bmp_name1)
else:
# Bitmap with two icon
bmp1 = SearchBitmap(bmp_name1)
bmp2 = SearchBitmap(bmp_name2)
if bmp1 is not None and bmp2 is not None:
# Calculate bitmap size
width = bmp1.GetWidth() + bmp2.GetWidth() - 1
height = max(bmp1.GetHeight(), bmp2.GetHeight())
# Create bitmap with both icons
bmp = wx.EmptyBitmap(width, height)
dc = wx.MemoryDC()
dc.SelectObject(bmp)
dc.Clear()
dc.DrawBitmap(bmp1, 0, 0)
dc.DrawBitmap(bmp2, bmp1.GetWidth() - 1, 0)
dc.Destroy()
elif bmp1 is not None:
bmp = bmp1
elif bmp2 is not None:
bmp = bmp2
if bmp is not None:
BitmapLibrary[(bmp_name1, bmp_name2, size)] = bmp
return bmp
def save_bitmap(self, path):
context = wx.ClientDC( self )
memory = wx.MemoryDC( )
x, y = self.ClientSize
bitmap = wx.Bitmap( x, y, -1 )
memory.SelectObject( bitmap )
memory.Blit( 0, 0, x, y, context, 0, 0)
memory.SelectObject( wx.NullBitmap)
bitmap.SaveFile( path, wx.BITMAP_TYPE_PNG )
def draw_bitmap_rectangle(bitmap, faces):
"""Draw rectangle on bitmap."""
dc = wx.MemoryDC(bitmap.bmp)
dc.SetPen(wx.BLUE_PEN)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
dc.SetTextBackground('black')
dc.SetTextForeground('white')
dc.SetBackgroundMode(wx.SOLID)
dc.SetFont(wx.Font(8,
wx.FONTFAMILY_DEFAULT,
wx.FONTSTYLE_NORMAL,
wx.FONTWEIGHT_BOLD))
for face in faces:
dc.DrawRectangle(
face.rect.left * bitmap.scale,
face.rect.top * bitmap.scale,
face.rect.width * bitmap.scale,
face.rect.height * bitmap.scale,
)
if face.name:
text_width, text_height = dc.GetTextExtent(face.name)
dc.DrawText(face.name,
face.rect.left * bitmap.scale,
face.rect.top * bitmap.scale - text_height)
dc.SelectObject(wx.NullBitmap)
bitmap.bitmap.SetBitmap(bitmap.bmp)
def __init__(self, text, font=None):
self._text = text
mem_dc = wx.MemoryDC()
w, h, l = mem_dc.GetMultiLineTextExtent(text, font if font else Fonts.get("default"))
self._sizer = wx.BoxSizer()
self._sizer.Add(wx.Size(w, h))
def take_screenshot(self):
screen = wx.ScreenDC()
bmp = wx.Bitmap(Screenshot.SRC_W, Screenshot.SRC_H)
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, Screenshot.SRC_W, Screenshot.SRC_H, screen, Screenshot.OFFSET_X, Screenshot.OFFSET_Y)
return bmp
def create_background(self):
w,h = self.GetSize()
self.background_bitmap = wx.EmptyBitmap(w, h)
dc = wx.MemoryDC(self.background_bitmap)
gc = wx.GraphicsContext_Create(dc)
dc.SetBrush(wx.Brush("#FFFFFF"))
dc.Clear()
dc.DrawRectangle(0,0,w,h)
off = h // self.chnls // 2
gc.SetPen(wx.Pen('#000000', width=1, style=wx.SOLID))
gc.SetBrush(wx.Brush("#FFFFFF", style=wx.TRANSPARENT))
dc.SetTextForeground("#444444")
if sys.platform in "darwin":
font, ptsize = dc.GetFont(), dc.GetFont().GetPointSize()
font.SetPointSize(ptsize - 3)
dc.SetFont(font)
else:
font = dc.GetFont()
font.SetPointSize(8)
dc.SetFont(font)
tickstep = w // 10
if tickstep < 40:
timelabel = "%.1f"
elif tickstep < 80:
timelabel = "%.2f"
elif tickstep < 120:
timelabel = "%.3f"
else:
timelabel = "%.4f"
timestep = (self.end - self.begin) * 0.1
for i, samples in enumerate(self.img):
y = h // self.chnls * i
if len(samples):
gc.DrawLines(samples)
dc.SetPen(wx.Pen('#888888', width=1, style=wx.DOT))
dc.DrawLine(0, y+off, w, y+off)
# for j in range(10):
# dc.SetPen(wx.Pen('#888888', width=1, style=wx.DOT))
# dc.DrawLine(j*tickstep, 0, j*tickstep, h)
# dc.DrawText(timelabel % (self.begin+j*timestep), j*tickstep+2, h-y-12)
dc.SetPen(wx.Pen('#000000', width=1))
dc.DrawLine(0, h-y, w, h-y)
dc.SelectObject(wx.NullBitmap)
def DrawCommonElements(self, dc, buttons=None):
"""
Function that draw common graphics for every Viewers
@param dc: wx.DC object corresponding to Device context where drawing
common graphics
@param buttons: List of buttons to draw if different from default
(default None)
"""
# Get Viewer size
width, height = self.GetSize()
# Set dc styling for drop before or drop after highlight
dc.SetPen(HIGHLIGHT_DROP_PEN)
dc.SetBrush(HIGHLIGHT_DROP_BRUSH)
# Draw line at upper side of Viewer if highlight is drop before
if self.Highlight == HIGHLIGHT_BEFORE:
dc.DrawLine(0, 1, width - 1, 1)
# Draw line at lower side of Viewer if highlight is drop before
elif self.Highlight == HIGHLIGHT_AFTER:
dc.DrawLine(0, height - 1, width - 1, height - 1)
# If no specific buttons are defined, get default buttons
if buttons is None:
buttons = self.Buttons
# Draw buttons
for button in buttons:
button.Draw(dc)
# If graph dragging is processing
if self.ParentWindow.IsDragging():
destBBox = self.ParentWindow.GetDraggingAxesClippingRegion(self)
srcPos = self.ParentWindow.GetDraggingAxesPosition(self)
if destBBox.width > 0 and destBBox.height > 0:
srcPanel = self.ParentWindow.DraggingAxesPanel
srcBBox = srcPanel.GetAxesBoundingBox()
srcX = srcBBox.x - (srcPos.x if destBBox.x == 0 else 0)
srcY = srcBBox.y - (srcPos.y if destBBox.y == 0 else 0)
srcBmp = _convert_agg_to_wx_bitmap(
srcPanel.get_renderer(), None)
srcDC = wx.MemoryDC()
srcDC.SelectObject(srcBmp)
dc.Blit(destBBox.x, destBBox.y,
int(destBBox.width), int(destBBox.height),
srcDC, srcX, srcY)
def RefreshView(self):
self.RefreshCanvasPosition()
width, height = self.GraphicsWindow.GetVirtualSize()
bitmap = wx.EmptyBitmap(width, height)
dc = wx.BufferedDC(wx.ClientDC(self.GraphicsWindow), bitmap)
dc.Clear()
dc.BeginDrawing()
if self.DraggingAxesPanel is not None:
destBBox = self.DraggingAxesBoundingBox
srcBBox = self.DraggingAxesPanel.GetAxesBoundingBox()
srcBmp = _convert_agg_to_wx_bitmap(self.DraggingAxesPanel.get_renderer(), None)
srcDC = wx.MemoryDC()
srcDC.SelectObject(srcBmp)
dc.Blit(destBBox.x, destBBox.y,
int(destBBox.width), int(destBBox.height),
srcDC, srcBBox.x, srcBBox.y)
dc.EndDrawing()
if not self.Fixed or self.Force:
self.Force = False
refresh_graphics = True
else:
refresh_graphics = False
if self.DraggingAxesPanel is not None and self.DraggingAxesPanel not in self.GraphicPanels:
self.DraggingAxesPanel.RefreshViewer(refresh_graphics)
for panel in self.GraphicPanels:
if isinstance(panel, DebugVariableGraphicViewer):
panel.RefreshViewer(refresh_graphics)
else:
panel.RefreshViewer()
if self.CursorTick is not None:
tick = self.CursorTick
elif len(self.Ticks) > 0:
tick = self.Ticks[-1]
else:
tick = None
if tick is not None:
self.TickLabel.SetLabel(label=_("Tick: %d") % tick)
tick_duration = int(tick * self.Ticktime)
not_null = False
duration = ""
for value, format in [(tick_duration / DAY, _("%dd")),
((tick_duration % DAY) / HOUR, _("%dh")),
((tick_duration % HOUR) / MINUTE, _("%dm")),
((tick_duration % MINUTE) / SECOND, _("%ds"))]:
if value > 0 or not_null:
duration += format % value
not_null = True
duration += _("%03gms") % (float(tick_duration % SECOND) / MILLISECOND)
self.TickTimeLabel.SetLabel("t: %s" % duration)
else:
self.TickLabel.SetLabel("")
self.TickTimeLabel.SetLabel("")
self.TickSizer.Layout()
def draw(self, drawDC=None):
"""
Render the figure.
"""
# Render figure using agg
FigureCanvasAgg.draw(self)
# Get bitmap of figure rendered
self.bitmap = _convert_agg_to_wx_bitmap(self.get_renderer(), None)
if wx.VERSION < (3, 0, 0):
self.bitmap.UseAlpha()
# Create DC for rendering graphics in bitmap
destDC = wx.MemoryDC()
destDC.SelectObject(self.bitmap)
# Get Graphics Context for DC, for anti-aliased and transparent
# rendering
destGC = wx.GCDC(destDC)
destGC.BeginDrawing()
# Get canvas size and figure bounding box in canvas
width, height = self.GetSize()
bbox = self.GetAxesBoundingBox()
# If highlight to display is resize, draw thick grey line at bottom
# side of canvas
if self.Highlight == HIGHLIGHT_RESIZE:
destGC.SetPen(HIGHLIGHT_RESIZE_PEN)
destGC.SetBrush(HIGHLIGHT_RESIZE_BRUSH)
destGC.DrawRectangle(0, height - 5, width, 5)
# If highlight to display is merging graph, draw 50% transparent blue
# rectangle on left or right part of figure depending on highlight type
elif self.Highlight in [HIGHLIGHT_LEFT, HIGHLIGHT_RIGHT]:
destGC.SetPen(HIGHLIGHT_DROP_PEN)
destGC.SetBrush(HIGHLIGHT_DROP_BRUSH)
x_offset = (bbox.width / 2
if self.Highlight == HIGHLIGHT_RIGHT
else 0)
destGC.DrawRectangle(bbox.x + x_offset, bbox.y,
bbox.width / 2, bbox.height)
# Draw other Viewer common elements
self.DrawCommonElements(destGC, self.GetButtons())
destGC.EndDrawing()
self._isDrawn = True
self.gui_repaint(drawDC=drawDC)
def onTakeScreenShot(self, event):
"""
Takes a screenshot of the screen at give pos & size (rect).
Method based on a script by Andrea Gavana
"""
print('Taking screenshot...')
rect = self.GetRect()
# adjust widths for Linux (figured out by John Torres
# http://article.gmane.org/gmane.comp.python.wxpython/67327)
if sys.platform == 'linux2':
client_x, client_y = self.ClientToScreen((0, 0))
border_width = client_x - rect.x
title_bar_height = client_y - rect.y
rect.width += (border_width * 2)
rect.height += title_bar_height + border_width
# Create a DC for the whole screen area
dcScreen = wx.ScreenDC()
# Create a Bitmap that will hold the screenshot image later on
# Note that the Bitmap must have a size big enough to hold the screenshot
# -1 means using the current default colour depth
bmp = wx.EmptyBitmap(rect.width, rect.height)
#Create a memory DC that will be used for actually taking the screenshot
memDC = wx.MemoryDC()
# Tell the memory DC to use our Bitmap
# all drawing action on the memory DC will go to the Bitmap now
memDC.SelectObject(bmp)
# Blit (in this case copy) the actual screen on the memory DC
# and thus the Bitmap
memDC.Blit( 0, # Copy to this X coordinate
0, # Copy to this Y coordinate
rect.width, # Copy this width
rect.height, # Copy this height
dcScreen, # Where to copy from
rect.x, # What's the X offset in the original DC?
rect.y # What's the Y offset in the original DC?
)
# Select the Bitmap out of the memory DC by selecting a new
# uninitialized Bitmap
memDC.SelectObject(wx.NullBitmap)
img = bmp.ConvertToImage()
fileName = "myImage.png"
img.SaveFile(fileName, wx.BITMAP_TYPE_PNG)
print('...saving as png!')
def GetToolTipSize(self):
"""
Get tool tip size according to tip text and restriction
@return: wx.Size(tool_tip_width, tool_tip_height)
"""
max_width = max_height = 0
# Create a memory DC for calculating text extent
dc = wx.MemoryDC()
dc.SetFont(self.Font)
# Compute max tip text size
for line in self.Tip:
w, h = dc.GetTextExtent(line)
max_width = max(max_width, w)
max_height += h
return wx.Size(max_width + 4, max_height + 4)