Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Text antialiasing for mathtext (reopen) #26376

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions doc/users/next_whats_new/antialiasing_text_annotation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ Examples:
plt.text(0.5, 0.5, '6 inches x 2 inches', antialiased=True)
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5), antialiased=False)

If the text contains math expression, then antialiasing will be set by :rc:`text.antialiased`, and *antialiased* will have no effect
This applies to the whole text.
If the text contains math expression, *antialiased* applies to the whole text.
Examples:

.. code-block::
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/_mathtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def to_vector(self):
for x1, y1, x2, y2 in self.rects]
return VectorParse(w, h + d, d, gs, rs)

def to_raster(self):
def to_raster(self, antialiased=None):
# Metrics y's and mathtext y's are oriented in opposite directions,
# hence the switch between ymin and ymax.
xmin = min([*[ox + info.metrics.xmin for ox, oy, info in self.glyphs],
Expand All @@ -125,7 +125,7 @@ def to_raster(self):
for ox, oy, info in shifted.glyphs:
info.font.draw_glyph_to_bitmap(
image, ox, oy - info.metrics.iceberg, info.glyph,
antialiased=mpl.rcParams['text.antialiased'])
antialiased=antialiased)
for x1, y1, x2, y2 in shifted.rects:
height = max(int(y2 - y1) - 1, 0)
if height == 0:
Expand Down
3 changes: 2 additions & 1 deletion lib/matplotlib/backends/backend_agg.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ def draw_path(self, gc, path, transform, rgbFace=None):
def draw_mathtext(self, gc, x, y, s, prop, angle):
"""Draw mathtext using :mod:`matplotlib.mathtext`."""
ox, oy, width, height, descent, font_image = \
self.mathtext_parser.parse(s, self.dpi, prop)
self.mathtext_parser.parse(s, self.dpi, prop,
antialiased=gc.get_antialiased())

xd = descent * sin(radians(angle))
yd = descent * cos(radians(angle))
Expand Down
11 changes: 7 additions & 4 deletions lib/matplotlib/mathtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import functools
import logging

import matplotlib as mpl
from matplotlib import _api, _mathtext
from matplotlib.ft2font import LOAD_NO_HINTING
from matplotlib.font_manager import FontProperties
Expand Down Expand Up @@ -58,7 +59,7 @@ def __init__(self, output):
{"path": "vector", "agg": "raster", "macosx": "raster"},
output=output.lower())

def parse(self, s, dpi=72, prop=None):
def parse(self, s, dpi=72, prop=None, *, antialiased=None):
"""
Parse the given math expression *s* at the given *dpi*. If *prop* is
provided, it is a `.FontProperties` object specifying the "default"
Expand All @@ -74,10 +75,12 @@ def parse(self, s, dpi=72, prop=None):
# is mutable; key the cache using an internal copy (see
# text._get_text_metrics_with_cache for a similar case).
prop = prop.copy() if prop is not None else None
return self._parse_cached(s, dpi, prop)
if antialiased is None:
antialiased = mpl.rcParams['text.antialiased']
return self._parse_cached(s, dpi, prop, antialiased)

@functools.lru_cache(50)
def _parse_cached(self, s, dpi, prop):
def _parse_cached(self, s, dpi, prop, antialiased):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also fixes a latent bug where we would incorrectly hit the cache if the rcparam was changed between the first and subsequent calls!

from matplotlib.backends import backend_agg

if prop is None:
Expand All @@ -100,7 +103,7 @@ def _parse_cached(self, s, dpi, prop):
if self._output_type == "vector":
return output.to_vector()
elif self._output_type == "raster":
return output.to_raster()
return output.to_raster(antialiased=antialiased)


def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None,
Expand Down
9 changes: 8 additions & 1 deletion lib/matplotlib/mathtext.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,14 @@ from matplotlib.typing import ColorType

class MathTextParser:
def __init__(self, output: Literal["path", "agg", "raster", "macosx"]) -> None: ...
def parse(self, s: str, dpi: float = ..., prop: FontProperties | None = ...): ...
def parse(
self,
s: str,
dpi: float = ...,
prop: FontProperties | None = ...,
*,
antialiased: bool | None = ...
): ...

def math_to_image(
s: str,
Expand Down
16 changes: 16 additions & 0 deletions lib/matplotlib/tests/test_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -962,3 +962,19 @@ def test_text_antialiased_on_default_vs_manual(fig_test, fig_ref):

mpl.rcParams['text.antialiased'] = True
fig_ref.text(0.5, 0.5, '6 inches x 2 inches')


@check_figures_equal()
def test_text_math_antialiased_on_default_vs_manual(fig_test, fig_ref):
fig_test.text(0.5, 0.5, r"OutsideMath $I\'m \sqrt{2}$", antialiased=True)

mpl.rcParams['text.antialiased'] = True
fig_ref.text(0.5, 0.5, r"OutsideMath $I\'m \sqrt{2}$")


@check_figures_equal()
def test_text_math_antialiased_off_default_vs_manual(fig_test, fig_ref):
fig_test.text(0.5, 0.5, r"OutsideMath $I\'m \sqrt{2}$", antialiased=False)

mpl.rcParams['text.antialiased'] = False
fig_ref.text(0.5, 0.5, r"OutsideMath $I\'m \sqrt{2}$")
Comment on lines +967 to +980
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately, neither of these tests fail without this PR, so I'm not sure if they are testing what you want?

Copy link
Contributor Author

@stevezhang1999 stevezhang1999 Jul 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes.
Before this: For math text, whether we are using antialiasing is resolved when rendering (_mathtext.py::Output.to_raster()). Two test figures are saved after we executing theses codes, resulting two figures resolve to the same rcParams.
After this: When creating the text, antialiasing states are set by True or False if the user specifies the keyword argument. Otherwise, the state resolves to rcParams also at the creation time. That is, we no longer query rcParams when rendering.