GraphicsContext
图形上下文(GraphicsContext,GC)提供了对平台高级绘制功能的访问。它提供的功能有反走样,浮点 精度坐标系统,alpha混合,渐变刷子,还提供了少量高级方法。
示例说明
创建一个像StaticText的控件,但其有渐变的背景。
#-*-coding: UTF-8 -*-
#------------------------------------------------------
#Purpose: nothing....
#Author: 阿Bin先生
#Created: 2017年5月21日
#------------------------------------------------------
import wx
class PodLabel(wx.PyControl):
def __init__(self, parent, label, color):
super(PodLabel, self).__init__(parent,
style=wx.NO_BORDER)
# Attributes
self._label = label
self._color = color
# Event Handlers
self.Bind(wx.EVT_PAINT, self.OnPaint)
def DoGetBestSize(self):
txtsz = self.GetTextExtent(self._label)
size = wx.Size(txtsz[0] + 10, txtsz[1] + 6)
return size
def OnPaint(self, event):
"""Draws the Caption and border around the controls"""
dc = wx.PaintDC(self)
gcdc = wx.GCDC(dc)
gc = gcdc.GetGraphicsContext()
# Get the working rectangle we can draw in
rect = self.GetClientRect()
# Setup the GraphicsContext
pen = gc.CreatePen(wx.TRANSPARENT_PEN)
gc.SetPen(pen)
rgb = self._color.Get(False)
alpha = self._color.Alpha() *.2 # fade to transparent
color2 = wx.Colour(*rgb, alpha=alpha)
x1, y1 = rect.x, rect.y
y2 = y1 + rect.height
gradbrush = gc.CreateLinearGradientBrush(x1, y1,
x1, y2,
self._color,
color2)
gc.SetBrush(gradbrush)
# Draw the background
gc.DrawRoundedRectangle(rect.x, rect.y,
rect.width, rect.height,
rect.height/2)
# Use the GCDC to help draw the aa text
gcdc.DrawLabel(self._label, rect, wx.ALIGN_CENTER)
class MyFrame(wx.Frame):
def __init__(self, parent, *args, **kwargs):
super(MyFrame, self).__init__(parent, *args, **kwargs)
# Attributes
self.Panel = wx.Panel(self)
label = PodLabel(self.Panel, "GraphicsContext", wx.RED)
label.SetSize([100, 50])
class MyApp(wx.App):
def OnInit(self):
self.frame = MyFrame(None, title="GraphicsContext",size = [500, 500])
self.SetTopWindow(self.frame)
self.frame.Show()
return True
if __name__ == "__main__":
app = MyApp(False)
app.MainLoop()
运行结果:
示例分析
在OnPaint方法中,将PaintDC封装在一个GCDC中。wx.GCDC是一个内部使用GC的DC接口。
通过这个DC接口,使能够使用类似使用普通DC的方式使用GC。
GraphicsContext的CreateLinearGradientBrush方法生成一个渐变刷子。GraphicsContext的DrawRoundedRectangle绘制一个带圆角的矩形。