Lecture7_Text_Fonts_Pycairo_Detailed.pptx

kamalsmail1 0 views 13 slides Oct 08, 2025
Slide 1
Slide 1 of 13
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13

About This Presentation

lecture 7


Slide Content

Lecture 7: Text and Fonts in Pycairo Computer Graphics with Pycairo

Objectives - Learn text rendering in Pycairo - Understand font selection and styling - Apply alignment and positioning - Transform text with scaling and rotation

Text Basics in Pycairo • ctx.show_text('Hello') • Draws text at the current position • Requires move_to(x,y) first

Selecting Fonts ctx.select_font_face(family, slant, weight) • family: 'Sans', 'Serif', 'Monospace' • slant: NORMAL, ITALIC • weight: NORMAL, BOLD

Font Slant & Weight • Slant options: cairo.FONT_SLANT_NORMAL, ITALIC • Weight options: cairo.FONT_WEIGHT_NORMAL, BOLD

Font Size ctx.set_font_size(24) • Defines text size in user space units

Positioning Text ctx.move_to(x, y) ctx.show_text('Hello')

Measuring Text extents = ctx.text_extents('Hello') • extents.width, height, x_bearing, y_bearing • Useful for centering or alignment

Text Transformations • Use ctx.translate, ctx.rotate, ctx.scale before drawing text • Enables rotated or scaled text

Practical Example 1: Multi-style Text import cairo WIDTH, HEIGHT = 400, 200 surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, WIDTH, HEIGHT) ctx = cairo.Context (surface) ctx.move_to (50, 50) ctx.select_font_face ('Sans', cairo.FONT_SLANT_NORMAL , cairo.FONT_WEIGHT_NORMAL ) ctx.set_font_size (24) ctx.show_text ('Normal Text') ctx.move_to (50, 100) ctx.select_font_face ('Sans', cairo.FONT_SLANT_ITALIC , cairo.FONT_WEIGHT_NORMAL ) ctx.show_text ('Italic Text') ctx.move_to (50, 150) ctx.select_font_face ('Sans', cairo.FONT_SLANT_NORMAL , cairo.FONT_WEIGHT_BOLD ) ctx.show_text ('Bold Text') surface.write_to_png ('text_styles.png')

Practical Example 2: Centered and Rotated Text import math, cairo WIDTH, HEIGHT = 400, 400 surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, WIDTH, HEIGHT) ctx = cairo.Context (surface) ctx.set_font_size (32) text = 'Rotated Text' # Measure text extents extents = ctx.text_extents (text) x = (WIDTH - extents.width ) / 2 y = (HEIGHT - extents.height ) / 2 ctx.translate (WIDTH/2, HEIGHT/2) ctx.rotate ( math.pi /4) ctx.move_to (- extents.width /2, extents.height /2) ctx.show_text (text) surface.write_to_png ('rotated_text.png')

Best Practices • Always set font size and style before drawing • Use text_extents for precise alignment • Combine text with graphics for labels

Summary • ctx.show_text for text rendering • select_font_face and set_font_size for styling • move_to and text_extents for positioning • Transform text with scale, rotate, translate
Tags