Text Annotations

Other than geometrical shapes, ImageDraw also provides text annotation with the function text(xy, string):

>>> from PIL import Image, ImageDraw >>> img = Image.new('L', (160, 160), 255) >>> draw = ImageDraw.Draw(img) >>> draw.ellipse((o, 0, 160, 160), fill=128) >>> draw.text((80, 80), 'A long string') >>> img.show()

Originally, I had intended on having the text centered horizontally. However, the text string has width, so I require a method to calculate the width and height of the text in pixels. Once I have the width and height, I can draw the text at location (80 - width/2, 80 - height/2). This is done using the function textsize():

>>> from PIL import Image, ImageDraw

>>> draw.ellipse((o, 0, 160, 160), fill=128)

>>> draw.text((80-width/2, 80-height/2), s) >>> img.show()

Figure 9-2 shows the results with and without taking into consideration the string width and height.

Figure 9-2. Text annotation using text() and textsize()

Was this article helpful?

0 0

Post a comment