java.awt.font.TextLayout Java Examples

The following examples show how to use java.awt.font.TextLayout. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TextArea.java    From pdfxtk with Apache License 2.0 6 votes vote down vote up
public void paintObject(Graphics2D g, double scale) {
     Rectangle bounds = getBounds(scale);

     if (style != null) style.setStyle(g);
     Style[] styles = context.flagger.getStyles(element);
     for (int i = 0; i < styles.length; i++) {
styles[i].setStyle(g);
     }

     if (style.isFilled()) {
Color c = g.getColor();
g.setColor(style.getBackground());
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
g.setColor(c);
     }

     Point[] tp = getTextPositions(scale);
     TextLayout[] tl = getTextLines(scale);
     for (int i = 0; i < tp.length; i++) {
tl[i].draw(g, tp[i].x, tp[i].y);
     }
   }
 
Example #2
Source File: CompositionArea.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private Rectangle getCaretRectangle(TextHitInfo caret) {
    int caretLocation = 0;
    TextLayout layout = composedTextLayout;
    if (layout != null) {
        caretLocation = Math.round(layout.getCaretInfo(caret)[0]);
    }
    Graphics g = getGraphics();
    FontMetrics metrics = null;
    try {
        metrics = g.getFontMetrics();
    } finally {
        g.dispose();
    }
    return new Rectangle(TEXT_ORIGIN_X + caretLocation,
                         TEXT_ORIGIN_Y - metrics.getAscent(),
                         0, metrics.getAscent() + metrics.getDescent());
}
 
Example #3
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override protected void paintComponent(Graphics g) {
  Graphics2D g2 = (Graphics2D) g.create();
  Font font = getFont();
  Insets ins = getInsets();
  Dimension d = getSize();
  int w = d.width - ins.left - ins.right;
  if (w != prevWidth) {
    prevWidth = w;
    layout = new TextLayout(getText(), font, g2.getFontRenderContext()).getJustifiedLayout((float) w);
  }
  g2.setPaint(getBackground());
  g2.fillRect(0, 0, d.width, d.height);
  g2.setPaint(getForeground());
  // int baseline = getBaseline(d.width, d.height);
  float baseline = ins.top + font.getSize2D();
  layout.draw(g2, (float) ins.left, baseline);
  g2.dispose();
}
 
Example #4
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override protected void paintComponent(Graphics g) {
  Graphics2D g2 = (Graphics2D) g.create();
  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  g2.setPaint(getForeground());
  g2.setFont(getFont());

  SwingUtilities.calculateInnerArea(this, RECT);
  float x = RECT.x;
  float y = RECT.y;
  int w = RECT.width;

  AttributedString as = new AttributedString(getText());
  as.addAttribute(TextAttribute.FONT, getFont()); // TEST: .deriveFont(at));
  // TEST: as.addAttribute(TextAttribute.TRANSFORM, at);
  AttributedCharacterIterator aci = as.getIterator();
  FontRenderContext frc = g2.getFontRenderContext();
  LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);

  while (lbm.getPosition() < aci.getEndIndex()) {
    TextLayout tl = lbm.nextLayout(w);
    tl.draw(g2, x, y + tl.getAscent());
    y += tl.getDescent() + tl.getLeading() + tl.getAscent();
  }
  g2.dispose();
}
 
Example #5
Source File: TextMeasureTests.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLExContext tlctx = (TLExContext)ctx;
    TextLayout tl = tlctx.tl;
    TextHitInfo[] hits = tlctx.hits;
    Rectangle2D lb = tlctx.lb;
    Shape s;
    if (hits.length < 3) {
        do {
            s = tl.getVisualHighlightShape(hits[0], hits[hits.length - 1], lb);
        } while (--numReps >= 0);
    } else {
        do {
            for (int i = 3; i < hits.length; ++i) {
                s = tl.getVisualHighlightShape(hits[i-3], hits[i], lb);
            }
        } while (--numReps >= 0);
    }
}
 
Example #6
Source File: TextMeasureTests.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLExContext tlctx = (TLExContext)ctx;
    TextLayout tl = tlctx.tl;
    int len = tlctx.text.length();
    Rectangle2D lb = tlctx.lb;
    Shape s;
    if (len < 3) {
        do {
            s = tl.getLogicalHighlightShape(0, len, lb);
        } while (--numReps >= 0);
    } else {
        do {
            for (int i = 3; i < len; ++i) {
                s = tl.getLogicalHighlightShape(i-3, i, lb);
            }
        } while (--numReps >= 0);
    }
}
 
Example #7
Source File: SigPainter.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
private void paintWord (WordInter word,
                        FontInfo lineMeanFont)
{
    if (lineMeanFont != null) {
        Font font = new TextFont(lineMeanFont);
        FontRenderContext frc = g.getFontRenderContext();
        TextLayout layout = new TextLayout(word.getValue(), font, frc);
        setColor(word);

        if (word.getValue().length() > 2) {
            paint(layout, word.getLocation(), BASELINE_LEFT);
        } else {
            paint(layout, word.getCenter(), AREA_CENTER);
        }
    }
}
 
Example #8
Source File: TextMeasureTests.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLExContext tlctx = (TLExContext)ctx;
    TextLayout tl = tlctx.tl;
    int len = tlctx.text.length();
    Rectangle2D lb = tlctx.lb;
    Shape s;
    if (len < 3) {
        do {
            s = tl.getLogicalHighlightShape(0, len, lb);
        } while (--numReps >= 0);
    } else {
        do {
            for (int i = 3; i < len; ++i) {
                s = tl.getLogicalHighlightShape(i-3, i, lb);
            }
        } while (--numReps >= 0);
    }
}
 
Example #9
Source File: MainPanel.java    From java-swing-tips with MIT License 6 votes vote down vote up
@Override protected void paintComponent(Graphics g) {
  super.paintComponent(g);
  int w = getWidth();
  int h = getHeight();
  g.setColor(Color.WHITE);
  g.fillRect(0, 0, w, h);

  Graphics2D g2 = (Graphics2D) g.create();
  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

  FontRenderContext frc = g2.getFontRenderContext();
  Shape shape = new TextLayout(text, getFont(), frc).getOutline(null);
  Rectangle2D b = shape.getBounds2D();
  double cx = w / 2d - b.getCenterX();
  double cy = h / 2d - b.getCenterY();
  AffineTransform toCenterAtf = AffineTransform.getTranslateInstance(cx, cy);

  Shape s = toCenterAtf.createTransformedShape(shape);
  g2.setPaint(Color.BLACK);
  g2.fill(s);
  Rectangle2D clip = new Rectangle2D.Double(b.getX(), b.getY(), b.getWidth(), b.getHeight() / 2d);
  g2.setClip(toCenterAtf.createTransformedShape(clip));
  g2.setPaint(Color.RED);
  g2.fill(s);
  g2.dispose();
}
 
Example #10
Source File: ArabicDiacriticTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
static void measureText() {
    Font font = new Font(FONT, Font.PLAIN, 36);
    if (!font.getFamily(Locale.ENGLISH).equals(FONT)) {
        return;
    }
    FontRenderContext frc = new FontRenderContext(null, false, false);
    TextLayout tl1 = new TextLayout(STR1, font, frc);
    TextLayout tl2 = new TextLayout(STR2, font, frc);
    Rectangle r1 = tl1.getPixelBounds(frc, 0f, 0f);
    Rectangle r2 = tl2.getPixelBounds(frc, 0f, 0f);
    if (r1.height > r2.height) {
        System.out.println(font);
        System.out.println(r1);
        System.out.println(r2);
        throw new RuntimeException("BAD BOUNDS");
    }
}
 
Example #11
Source File: Font.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * Returns the logical bounds of the specified array of characters
 * in the specified <code>FontRenderContext</code>.  The logical
 * bounds contains the origin, ascent, advance, and height, which
 * includes the leading.  The logical bounds does not always enclose
 * all the text.  For example, in some languages and in some fonts,
 * accent marks can be positioned above the ascent or below the
 * descent.  To obtain a visual bounding box, which encloses all the
 * text, use the {@link TextLayout#getBounds() getBounds} method of
 * <code>TextLayout</code>.
 * <p>Note: The returned bounds is in baseline-relative coordinates
 * (see {@link java.awt.Font class notes}).
 * @param chars an array of characters
 * @param beginIndex the initial offset in the array of
 * characters
 * @param limit the end offset in the array of characters
 * @param frc the specified <code>FontRenderContext</code>
 * @return a <code>Rectangle2D</code> that is the bounding box of the
 * specified array of characters in the specified
 * <code>FontRenderContext</code>.
 * @throws IndexOutOfBoundsException if <code>beginIndex</code> is
 *         less than zero, or <code>limit</code> is greater than the
 *         length of <code>chars</code>, or <code>beginIndex</code>
 *         is greater than <code>limit</code>.
 * @see FontRenderContext
 * @see Font#createGlyphVector
 * @since 1.2
 */
public Rectangle2D getStringBounds(char [] chars,
                                int beginIndex, int limit,
                                   FontRenderContext frc) {
    if (beginIndex < 0) {
        throw new IndexOutOfBoundsException("beginIndex: " + beginIndex);
    }
    if (limit > chars.length) {
        throw new IndexOutOfBoundsException("limit: " + limit);
    }
    if (beginIndex > limit) {
        throw new IndexOutOfBoundsException("range length: " +
                                            (limit - beginIndex));
    }

    // this code should be in textlayout
    // quick check for simple text, assume GV ok to use if simple

    boolean simple = values == null ||
        (values.getKerning() == 0 && values.getLigatures() == 0 &&
          values.getBaselineTransform() == null);
    if (simple) {
        simple = ! FontUtilities.isComplexText(chars, beginIndex, limit);
    }

    if (simple) {
        GlyphVector gv = new StandardGlyphVector(this, chars, beginIndex,
                                                 limit - beginIndex, frc);
        return gv.getLogicalBounds();
    } else {
        // need char array constructor on textlayout
        String str = new String(chars, beginIndex, limit - beginIndex);
        TextLayout tl = new TextLayout(str, this, frc);
        return new Rectangle2D.Float(0, -tl.getAscent(), tl.getAdvance(),
                                     tl.getAscent() + tl.getDescent() +
                                     tl.getLeading());
    }
}
 
Example #12
Source File: SunGraphics2D.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void drawString(String str, float x, float y) {
    if (str == null) {
        throw new NullPointerException("String is null");
    }

    if (font.hasLayoutAttributes()) {
        if (str.length() == 0) {
            return;
        }
        new TextLayout(str, font, getFontRenderContext()).draw(this, x, y);
        return;
    }

    try {
        textpipe.drawString(this, str, x, y);
    } catch (InvalidPipeException e) {
        try {
            revalidateAll();
            textpipe.drawString(this, str, x, y);
        } catch (InvalidPipeException e2) {
            // Still catching the exception; we are not yet ready to
            // validate the surfaceData correctly.  Fail for now and
            // try again next time around.
        }
    } finally {
        surfaceData.markDirty();
    }
}
 
Example #13
Source File: FontPanel.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void tlDrawLine( Graphics2D g2, TextLayout tl,
                                   float baseX, float baseY ) {
    /// ABP - keep track of old tform, restore it later
    AffineTransform oldTx = null;
    oldTx = g2.getTransform();
    g2.translate( baseX, baseY );
    g2.transform( getAffineTransform( g2Transform ) );

    tl.draw( g2, (float) 0, (float) 0 );

    /// ABP - restore old tform
    g2.setTransform ( oldTx );

}
 
Example #14
Source File: TextMeasureTests.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLExContext tlctx = (TLExContext)ctx;
    TextLayout tl = tlctx.tl;
    TextHitInfo[] hits = tlctx.hits;
    do {
        for (int i = 0; i < hits.length; ++i) {
            tl.getCaretInfo(hits[i]);
        }
    } while (--numReps >= 0);
}
 
Example #15
Source File: PathGraphics.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void drawString(String str, float x, float y) {
    if (str.length() == 0) {
        return;
    }
    TextLayout layout =
        new TextLayout(str, getFont(), getFontRenderContext());
    layout.draw(this, x, y);
}
 
Example #16
Source File: TextMeasureTests.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLContext tlctx = (TLContext)ctx;
    TextLayout tl = tlctx.tl;
    float ht = 0;
    do {
        ht += tl.getAscent();
    } while (--numReps >= 0);
}
 
Example #17
Source File: TextMeasureTests.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLContext tlctx = (TLContext)ctx;
    TextLayout tl = tlctx.tl;
    Rectangle2D r;
    do {
        r = tl.getBounds();
    } while (--numReps >= 0);
}
 
Example #18
Source File: TextRenderTests.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLContext tlctx = (TLContext)ctx;
    Graphics2D g2d = tlctx.g2d;
    TextLayout tl = tlctx.tl;
    do {
        tl.draw(g2d, 40, 40);
    } while (--numReps >= 0);
}
 
Example #19
Source File: Font.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the logical bounds of the specified array of characters
 * in the specified {@code FontRenderContext}.  The logical
 * bounds contains the origin, ascent, advance, and height, which
 * includes the leading.  The logical bounds does not always enclose
 * all the text.  For example, in some languages and in some fonts,
 * accent marks can be positioned above the ascent or below the
 * descent.  To obtain a visual bounding box, which encloses all the
 * text, use the {@link TextLayout#getBounds() getBounds} method of
 * {@code TextLayout}.
 * <p>Note: The returned bounds is in baseline-relative coordinates
 * (see {@link java.awt.Font class notes}).
 * @param chars an array of characters
 * @param beginIndex the initial offset in the array of
 * characters
 * @param limit the end offset in the array of characters
 * @param frc the specified {@code FontRenderContext}
 * @return a {@code Rectangle2D} that is the bounding box of the
 * specified array of characters in the specified
 * {@code FontRenderContext}.
 * @throws IndexOutOfBoundsException if {@code beginIndex} is
 *         less than zero, or {@code limit} is greater than the
 *         length of {@code chars}, or {@code beginIndex}
 *         is greater than {@code limit}.
 * @see FontRenderContext
 * @see Font#createGlyphVector
 * @since 1.2
 */
public Rectangle2D getStringBounds(char [] chars,
                                int beginIndex, int limit,
                                   FontRenderContext frc) {
    if (beginIndex < 0) {
        throw new IndexOutOfBoundsException("beginIndex: " + beginIndex);
    }
    if (limit > chars.length) {
        throw new IndexOutOfBoundsException("limit: " + limit);
    }
    if (beginIndex > limit) {
        throw new IndexOutOfBoundsException("range length: " +
                                            (limit - beginIndex));
    }

    // this code should be in textlayout
    // quick check for simple text, assume GV ok to use if simple

    boolean simple = values == null ||
        (values.getKerning() == 0 && values.getLigatures() == 0 &&
          values.getBaselineTransform() == null);
    if (simple) {
        simple = ! FontUtilities.isComplexText(chars, beginIndex, limit);
    }

    if (simple) {
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(this, frc);
        return metrics.getSimpleBounds(chars, beginIndex, limit-beginIndex);
    } else {
        // need char array constructor on textlayout
        String str = new String(chars, beginIndex, limit - beginIndex);
        TextLayout tl = new TextLayout(str, this, frc);
        return new Rectangle2D.Float(0, -tl.getAscent(), tl.getAdvance(),
                                     tl.getAscent() + tl.getDescent() +
                                     tl.getLeading());
    }
}
 
Example #20
Source File: SunGraphics2D.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public void drawString(String str, int x, int y) {
    if (str == null) {
        throw new NullPointerException("String is null");
    }

    if (font.hasLayoutAttributes()) {
        if (str.length() == 0) {
            return;
        }
        new TextLayout(str, font, getFontRenderContext()).draw(this, x, y);
        return;
    }

    try {
        textpipe.drawString(this, str, x, y);
    } catch (InvalidPipeException e) {
        try {
            revalidateAll();
            textpipe.drawString(this, str, x, y);
        } catch (InvalidPipeException e2) {
            // Still catching the exception; we are not yet ready to
            // validate the surfaceData correctly.  Fail for now and
            // try again next time around.
        }
    } finally {
        surfaceData.markDirty();
    }
}
 
Example #21
Source File: TextMeasureTests.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLContext tlctx = (TLContext)ctx;
    TextLayout tl = tlctx.tl;
    double wid = 0;
    do {
        wid += tl.getAdvance();
    } while (--numReps >= 0);
}
 
Example #22
Source File: TextMeasureTests.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLContext tlctx = (TLContext)ctx;
    TextLayout tl = tlctx.tl;
    Shape s;
    do {
        s = tl.getOutline(null);
    } while (--numReps >= 0);
}
 
Example #23
Source File: TextMeasureTests.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLContext tlctx = (TLContext)ctx;
    TextLayout tl = tlctx.tl;
    double wid = 0;
    do {
        wid += tl.getAdvance();
    } while (--numReps >= 0);
}
 
Example #24
Source File: GlyphVectorOutline.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void drawString(Graphics2D g, Font font, String value, float x, float y) {
    AttributedString str = new AttributedString(value);
    str.addAttribute(TextAttribute.FOREGROUND, Color.BLACK);
    str.addAttribute(TextAttribute.FONT, font);
    FontRenderContext frc = new FontRenderContext(null, true, true);
    TextLayout layout = new LineBreakMeasurer(str.getIterator(), frc).nextLayout(Integer.MAX_VALUE);
    layout.draw(g, x, y);
}
 
Example #25
Source File: TextMeasureTests.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLContext tlctx = (TLContext)ctx;
    TextLayout tl = tlctx.tl;
    double wid = 0;
    do {
        wid += tl.getAdvance();
    } while (--numReps >= 0);
}
 
Example #26
Source File: PathGraphics.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void drawString(AttributedCharacterIterator iterator,
                       float x, float y) {
    if (iterator == null) {
        throw
            new NullPointerException("attributedcharacteriterator is null");
    }
    TextLayout layout =
        new TextLayout(iterator, getFontRenderContext());
    layout.draw(this, x, y);
}
 
Example #27
Source File: TextMeasureTests.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLExContext tlctx = (TLExContext)ctx;
    TextLayout tl = tlctx.tl;
    TextHitInfo[] hits = tlctx.hits;
    Shape s;
    do {
        for (int i = 0; i < hits.length; ++i) {
            s = tl.getCaretShape(hits[i]);
        }
    } while (--numReps >= 0);
}
 
Example #28
Source File: CompositionArea.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void paint(Graphics g) {
    super.paint(g);
    g.setColor(getForeground());
    TextLayout layout = composedTextLayout;
    if (layout != null) {
        layout.draw((Graphics2D) g, TEXT_ORIGIN_X, TEXT_ORIGIN_Y);
    }
    if (caret != null) {
        Rectangle rectangle = getCaretRectangle(caret);
        g.setXORMode(getBackground());
        g.fillRect(rectangle.x, rectangle.y, 1, rectangle.height);
        g.setPaintMode();
    }
}
 
Example #29
Source File: SVGImageExporter.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Rectangle2D getStringBounds(@Nonnull final String str) {
  if (str.isEmpty()) {
    return this.context.getFontMetrics().getStringBounds("", this.context);
  } else {
    final TextLayout textLayout = new TextLayout(str, this.context.getFont(), this.context.getFontRenderContext());
    return new Rectangle2D.Float(0, -textLayout.getAscent(), textLayout.getAdvance(), textLayout.getAscent() + textLayout.getDescent() + textLayout.getLeading());
  }
}
 
Example #30
Source File: TextMeasureTests.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void runTest(Object ctx, int numReps) {
    TLExContext tlctx = (TLExContext)ctx;
    TextLayout tl = tlctx.tl;
    TextHitInfo[] hits = tlctx.hits;
    TextHitInfo hit;
    do {
        for (int i = 0; i < hits.length; ++i) {
            hit = tl.getNextLeftHit(hits[i]);
        }
    } while (--numReps >= 0);
}