1

Is there a way using ImageFont module of Python Image Library to make strikethrough text?

my_font = ImageFont.truetype("Trebuchet MS Bold.ttf", 13)
# DO SOMETHING HERE TO MAKE FONT STRIKETHROUGH?
draw.text((x,y), text, fill=(16, 31, 83), font=my_font)

The solution mentioned here does not work. The code below produces then the following image.

enter image description here

from PIL import Image, ImageDraw, ImageFont

def draw_strikethrough_text():
    hello = 'Hello '
    cruel = 'cruel'
    world = ' world'

    cruel = strikethrough(cruel)

    img = Image.new('RGBA', (200, 100), "white")
    draw = ImageDraw.Draw(img)
    hw_font = ImageFont.truetype("Trebuchet MS.ttf", 13)

    textsize_hello = draw.textsize(hello, hw_font)[0]
    textsize_cruel = draw.textsize(cruel, hw_font)[0]

    margin = 20
    x_hello = margin
    x_cruel = x_hello + textsize_hello
    x_world = x_cruel + textsize_cruel
    y = margin

    draw.text((x_hello, y), hello, fill=(60, 60, 60), font=hw_font)
    draw.text((x_cruel, y), cruel, fill=(60, 60, 60), font=hw_font)
    draw.text((x_world, y), world, fill=(60, 60, 60), font=hw_font)

    img.save('img/hello_cruel_world.png', quality=95, optimize=True)

def strikethrough(text):
    return '\u0336'.join(text) + '\u0336'

if __name__ == '__main__':
    draw_strikethrough_text()
Community
  • 1
  • 1
physicalattraction
  • 6,485
  • 10
  • 63
  • 122
  • 1
    Can you show us the *actual code* that doesn't work and what, exactly, doesn't work about it - does it concatenate as in the example, or do something else? – SiHa Jul 09 '15 at 11:31
  • possible duplicate of [How to use unicode characters with PIL?](http://stackoverflow.com/questions/18942605/how-to-use-unicode-characters-with-pil). Specifically, you need to use `u'\u0336'` and ensure you're using a unicode font. Doing this works on my machine with Arial, but **not** Trebuchet MS – SiHa Jul 09 '15 at 12:33
  • 1
    The point is that using Unicode for this is a non-solution. Can't you just let `w, h = textsize_cruel` and then draw a line from `(x, y+h/2)` to `(x+w, y+h/2)`, horizontally through the center of the box containing the word? – Lynn Jul 09 '15 at 13:40
  • (This will obviously cause problems if the text you're drawing contains newlines, though.) – Lynn Jul 09 '15 at 13:41
  • The thing you mention with manually drawing a line was indeed already my workaround. – physicalattraction Jul 09 '15 at 16:40

0 Answers0