Python/wxPython/Graphics

From Fundamental Ramen
Jump to navigation Jump to search

Known Issues

  • wx.DC cannot use matrix on macOS
  • pycairo cannot use FreeType font
  • wx.lib.wxcairo.FontFaceFromFont(wxfont) is the best way to set font
  • If draw something using both wx.DC and cairo.Context, some shape or text would be disappered.

Set font and show text

import subprocess

import cairo
import wx
import wx.lib.wxcairo

WIDTH = 400
HEIGHT = 300

surface = cairo.ImageSurface(
    cairo.FORMAT_RGB24,
    WIDTH,
    HEIGHT
)
ctx = cairo.Context(surface)
ctx.rectangle(0, 0, WIDTH, HEIGHT)
ctx.set_source_rgb(0.8, 0.8, 1)
ctx.fill()

# Drawing code
app = wx.App()
wfont = wx.Font(
    13,
    wx.FONTFAMILY_DEFAULT,
    wx.FONTSTYLE_NORMAL,
    wx.FONTWEIGHT_NORMAL,
    False,
    '蘋果儷細宋'
)
cfont = wx.lib.wxcairo.FontFaceFromFont(wfont)
ctx.set_font_face(cfont)
ctx.set_font_size(13)
ctx.set_source_rgb(0, 0, 0)
ctx.move_to(20, 80)
ctx.show_text('Your grand mom, 林啊罵勒')
# End of drawing code

surface.write_to_png('text.png')
subprocess.run(['open', 'text.png'])

Draw line by Cairo

#!/usr/bin/env python3
import wx
import wx.lib.wxcairo

class MyApp(wx.App):

    def OnInit(self):
        frame = wx.Frame(None, -1, 'Hello World!')
        frame.Bind(wx.EVT_PAINT, self.OnPaint)
        frame.Show()
        self.mainFrame = frame
        return True

    def OnPaint(self, evt):
        # dc = wx.BufferedPaintDC(self.mainFrame)
        # dc = wx.PaintDC(self.mainFrame)
        # dc = wx.ClientDC(self.mainFrame)
        dc = wx.WindowDC(self.mainFrame)
        ctx = wx.lib.wxcairo.ContextFromDC(dc)
        ctx.set_line_width(5)
        ctx.move_to(10, 20)
        ctx.line_to(200, 20)
        ctx.stroke()

if __name__ == '__main__':
    app = MyApp()
    app.MainLoop()

Draw line by PaintDC

#!/usr/bin/env python3
import wx

class MyApp(wx.App):

    def OnInit(self):
        frame = wx.Frame(None, -1, 'Hello World!')
        frame.Bind(wx.EVT_PAINT, self.OnPaint)
        frame.Show()
        self.mainFrame = frame
        return True

    def OnPaint(self, evt):
        dc = wx.PaintDC(self.mainFrame)
        dc.DrawLine(10, 10, 200, 10)

if __name__ == '__main__':
    app = MyApp()
    app.MainLoop()

wx.DC hierarchy