wxPython之wx.DC繪制形狀
更新時間:2019年11月19日 11:29:30 作者:阿兵-AI醫(yī)療
這篇文章主要為大家詳細介紹了wxPython之wx.DC繪制形狀,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了wxPython繪制形狀的具體代碼,供大家參考,具體內容如下
繪制形狀
除了繪制文本和位圖,DC也可以繪制任意的形狀和線。這允許我們完全自定義窗口部件和控件的外觀。
示例說明
利用PaintDC創(chuàng)建一個簡單笑臉控件。
#-*-coding: UTF-8 -*-
#------------------------------------------------------
#Purpose: nothing....
#Author: 阿Bin先生
#Created: 2017年5月21日
#------------------------------------------------------
import wx
class Smiley(wx.PyControl):
def __init__(self, parent, size=(100, 100)):
super(Smiley, self).__init__(parent,
size=size,
style=wx.NO_BORDER)
# Event Handlers
self.Bind(wx.EVT_PAINT, self.OnPaint)
def OnPaint(self, event):
"""Draw the image on to the panel"""
dc = wx.PaintDC(self) # Must create a PaintDC
# Get the working rectangle we can draw in
rect = self.GetClientRect()
# Setup the DC
dc.SetPen(wx.BLACK_PEN) # for drawing lines / borders
yellowbrush = wx.Brush(wx.Colour(255, 255, 0))
dc.SetBrush(yellowbrush) # Yellow fill
cx = (rect.width / 2) + rect.x
cy = (rect.width / 2) + rect.y
radius = min(rect.width, rect.height) / 2
dc.DrawCircle(cx, cy, radius)
eyesz = (rect.width / 8, rect.height / 8)
eyepos = (cx / 2, cy / 2)
dc.SetBrush(wx.BLUE_BRUSH)
dc.DrawRectangle(eyepos[0], eyepos[1],
eyesz[0], eyesz[1])
eyepos = (eyepos[0] + (cx - eyesz[0]), eyepos[1])
dc.DrawRectangle(eyepos[0], eyepos[1],
eyesz[0], eyesz[1])
dc.SetBrush(yellowbrush)
startpos = (cx / 2, (cy / 2) + cy)
endpos = (cx + startpos[0], startpos[1])
dc.DrawArc(startpos[0], startpos[1],
endpos[0], endpos[1], cx, cy)
dc.SetPen(wx.TRANSPARENT_PEN)
dc.DrawRectangle(startpos[0], cy,
endpos[0] - startpos[0],
startpos[1] - cy)
class MyFrame(wx.Frame):
def __init__(self, parent, *args, **kwargs):
super(MyFrame, self).__init__(parent, *args, **kwargs)
# Attributes
self.Panel = wx.Panel(self)
Smiley(self.Panel)
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(None, title="DrawShapes",size = [500, 500])
self.SetTopWindow(self.frame)
self.frame.Show()
return True
if __name__ == "__main__":
app = MyApp(False)
app.MainLoop()
運行結果:

示例分析
DC的SetPen用來繪制線條和形狀的邊框。DC的SetBrush用來填充顏色。首先使用DCdeDrawCircle繪制一個黑色邊框的黃色圓,表示頭。然后使用DrawRectangle方法繪制藍色矩形,表示眼睛。最后使用DC的DrawArch方法繪制扇形,因為只想用圓弧來表示微笑,所以用矩形覆蓋圓弧兩端的兩條半徑線。
常用的基本繪制函數(shù)


以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

