wxPython之GraphicsContext

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绘制一个带圆角的矩形。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值