#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2022/03/25 21:44:30 +0900> """ pycairo clipping sample. * Windows10 x64 21H2 + Python 2.7.18 32bit + pycairo 1.8.10 * Windows10 x64 21H2 + Python 3.9.11 64bit + pycairo 1.21.0 """ import cairo import math def draw_rounder_rectangle(ctx, x, y, w, h, ra): """Set sub path rounded rectangle.""" deg = math.pi / 180.0 ctx.new_sub_path() ctx.arc(x + w - ra, y + ra, ra, -90 * deg, 0 * deg) ctx.arc(x + w - ra, y + h - ra, ra, 0 * deg, 90 * deg) ctx.arc(x + ra, y + h - ra, ra, 90 * deg, 180 * deg) ctx.arc(x + ra, y + ra, ra, 180 * deg, 270 * deg) ctx.close_path() def main(): w, h = 256, 256 # draw base surface base = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) c = cairo.Context(base) # fill background c.set_source_rgb(0.5, 0.5, 0.5) c.rectangle(0, 0, w, h) c.fill() # draw lines c.set_source_rgb(0, 1.0, 0) c.set_line_width(6) for y in range(0, h, 32): c.move_to(0, y) c.line_to(w, y) c.stroke() ims = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) c = cairo.Context(ims) c.set_source_surface(base, 0, 0) # set clipping path s = 16 draw_rounder_rectangle(c, s, s, w - s * 2, h - s * 2, 32) # clipping c.clip() c.paint() # save surface as png image ims.write_to_png("01_clipping_result.png") if __name__ == '__main__': main()