Using a text as a Path
TextPath creates a Path that is the outline of the characters of a text.
The resulting path can be employed e.g. as a clip path for an image.

from PIL import Image
import matplotlib.pyplot as
plt
import
numpy
as
np
from
matplotlib.cbook
import
from
matplotlib.image
import
from
matplotlib.offsetbox
import
,
,
from
matplotlib.patches
import
,
from
matplotlib.text
import
from
matplotlib.transforms
import
class
PathClippedImagePatch
(
):
"""
The given image is used to draw the face of the patch. Internally,
it uses BboxImage whose clippath set to the path of the patch.
FIXME : The result is currently dpi dependent.
"""
def
__init__
(
self
,
path
,
bbox_image
,
**
kwargs
):
super
()
.
__init__
(
path
,
**
kwargs
)
self
.
bbox_image
=
(
self
.
get_window_extent
,
norm
=
None
,
origin
=
None
)
self
.
bbox_image
.
set_data
(
bbox_image
)
def
set_facecolor
(
self
,
color
):
"""Simply ignore facecolor."""
super
()
.
set_facecolor
(
"none"
)
def
draw
(
self
,
renderer
=
None
):
self
.
bbox_image
.
set_clip_path
(
self
.
_path
,
self
.
get_transform
())
self
.
bbox_image
.
draw
(
renderer
)
super
()
.
draw
(
renderer
)
if
__name__
==
"__main__"
:
,
(
,
)
=
(
2
)
=
(
(
"grace_hopper.jpg"
))
text_path
=
((
0
,
0
),
"!?"
,
size
=
150
)
p
=
(
text_path
,
,
ec
=
"k"
)
=
(
())
(
p
)
=
(
loc
=
'upper left'
,
child
=
,
frameon
=
True
,
borderpad
=
0.2
)
(
)
for
,
,
in
[
(
False
,
0.25
,
r
"textpath supports mathtext"
),
(
True
,
0.05
,
r
"textpath supports \TeX"
),
]:
text_path
=
((
0
,
0
),
,
size
=
20
,
=
)
=
(
text_path
,
ec
=
"w"
,
lw
=
3
,
fc
=
"w"
,
alpha
=
0.9
)
=
(
text_path
,
ec
=
"none"
,
fc
=
"k"
)
=
(
())
(
)
(
)
=
(
,
(
0.95
,
),
xycoords
=
'axes fraction'
,
boxcoords
=
"offset points"
,
box_alignment
=
(
1.
,
0.
),
frameon
=
False
,
)
(
)
([[
0
,
1
,
2
],
[
1
,
2
,
3
]],
cmap
=
"gist_gray_r"
,
interpolation
=
"bilinear"
,
aspect
=
"auto"
)
=
(
256
)
.
reshape
(
1
,
256
)
for
,
,
in
[
(
False
,
0.25
,
r
"$\left[\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}\right]$!"
),
(
True
,
0.75
,
r
"$\displaystyle\left[\sum_{n=1}^\infty"
r
"\frac{-e^{i\pi}}{2^n}\right]$!"
),
]:
text_path
=
((
0
,
0
),
,
size
=
40
,
=
)
text_patch
=
(
text_path
,
,
ec
=
"none"
)
=
(
text_patch
,
1
,
-
1
,
fc
=
"none"
,
ec
=
"0.6"
,
lw
=
3
)
=
(
text_patch
,
1
,
-
1
,
fc
=
"0.3"
,
ec
=
"none"
)
=
(
())
(
)
(
)
(
text_patch
)
=
(
,
(
,
0.5
),
box_alignment
=
(
0.5
,
0.5
))
(
)
(
0
,
1
)
(
0
,
1
)
()
Total running time of the script: (0 minutes 1.905 seconds)