From 879dde138298718c6d9f61c10189b30aa19fd4e8 Mon Sep 17 00:00:00 2001 From: Dimitry Ivanov Date: Thu, 4 Jul 2019 17:26:03 +0300 Subject: [PATCH] Scale down LaTeX formula if exceed canvas width (keep ratio) --- .../markwon/ext/latex/JLatexMathPlugin.java | 23 +++++++--- .../markwon/sample/latex/LatexActivity.java | 44 +++++++++---------- 2 files changed, 40 insertions(+), 27 deletions(-) diff --git a/markwon-ext-latex/src/main/java/io/noties/markwon/ext/latex/JLatexMathPlugin.java b/markwon-ext-latex/src/main/java/io/noties/markwon/ext/latex/JLatexMathPlugin.java index 291d361a..5d136ece 100644 --- a/markwon-ext-latex/src/main/java/io/noties/markwon/ext/latex/JLatexMathPlugin.java +++ b/markwon-ext-latex/src/main/java/io/noties/markwon/ext/latex/JLatexMathPlugin.java @@ -361,12 +361,25 @@ public class JLatexMathPlugin extends AbstractMarkwonPlugin { final Rect imageBounds = drawable.getResult().getBounds(); final int canvasWidth = drawable.getLastKnownCanvasWidth(); - // todo: scale down when formula is greater than width (keep ratio and apply height) + if (fitCanvas) { - if (fitCanvas - && imageBounds.width() < canvasWidth) { - // we increase only width (keep height as-is) - return new Rect(0, 0, canvasWidth, imageBounds.height()); + // we modify bounds only if `fitCanvas` is true + final int w = imageBounds.width(); + + if (w < canvasWidth) { + // increase width and center formula (keep height as-is) + return new Rect(0, 0, canvasWidth, imageBounds.height()); + } + + // @since 4.0.2 we additionally scale down the resulting formula (keeping the ratio) + // the thing is - JLatexMathDrawable will do it anyway, but it will modify its own + // bounds (which AsyncDrawable won't catch), thus leading to an empty space after the formula + if (w > canvasWidth) { + // here we must scale it down (keeping the ratio) + final float ratio = (float) w / imageBounds.height(); + final int h = (int) (canvasWidth / ratio + .5F); + return new Rect(0, 0, canvasWidth, h); + } } return imageBounds; diff --git a/sample/src/main/java/io/noties/markwon/sample/latex/LatexActivity.java b/sample/src/main/java/io/noties/markwon/sample/latex/LatexActivity.java index 7adee8e8..44d9aac3 100644 --- a/sample/src/main/java/io/noties/markwon/sample/latex/LatexActivity.java +++ b/sample/src/main/java/io/noties/markwon/sample/latex/LatexActivity.java @@ -66,29 +66,29 @@ public class LatexActivity extends Activity { // })) .usePlugin(JLatexMathPlugin.create(textView.getTextSize())) .build(); - - if (true) { -// final String l = "$$\n" + -// " P(X=r)=\\frac{\\lambda^r e^{-\\lambda}}{r!}\n" + -// "$$\n" + -// "\n" + -// "$$\n" + -// " P(Xr)=1-P(Xr)=1-P(X