Java 类java.awt.font.TextLayout 实例源码

项目:alevin-svn2    文件:LayerViewer.java   
@Override
public void paint(Graphics g) {
    Dimension d = vv.getSize();
    FontRenderContext frc = ((Graphics2D) g).getFontRenderContext();
    Font f = new Font("Times", Font.BOLD, 30);

    TextLayout tl = new TextLayout(str, f, frc);
    AffineTransform transform = new AffineTransform();
    transform.setToTranslation(d.width / 2, d.height / 2);
    transform.rotate(Math.toRadians(315));
    Shape shape = tl.getOutline(transform);
    g.translate(-shape.getBounds().width / 2,
            shape.getBounds().height / 2);
    g.setColor(Color.lightGray);
    ((Graphics2D) g).draw(shape);
}
项目:incubator-netbeans    文件:FoldView.java   
@Override
public float getPreferredSpan(int axis) {
    if (axis == View.X_AXIS) {
        String desc = fold.getDescription(); // For empty desc a single-space text layout is returned
        float advance = 0;
        if (desc.length() > 0) {
            TextLayout textLayout = getTextLayout();
            if (textLayout == null) {
                return 0f;
            }
            advance = textLayout.getAdvance();
        }
        return advance + (2 * EXTRA_MARGIN_WIDTH);
    } else {
        EditorView.Parent parent = (EditorView.Parent) getParent();
        return (parent != null) ? parent.getViewRenderContext().getDefaultRowHeight() : 0f;
    }
}
项目:openjdk-jdk10    文件:TextMeasureTests.java   
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);
    }
}
项目:jdk8u-jdk    文件:SunGraphics2D.java   
public void drawString(AttributedCharacterIterator iterator,
                       float x, float y) {
    if (iterator == null) {
        throw new NullPointerException("AttributedCharacterIterator is null");
    }
    if (iterator.getBeginIndex() == iterator.getEndIndex()) {
        return; /* nothing to draw */
    }
    TextLayout tl = new TextLayout(iterator, getFontRenderContext());
    tl.draw(this, x, y);
}
项目:incubator-netbeans    文件:TextLayoutUtils.java   
/**
     * Get real allocation (possibly not rectangular) of a part of layout.
     * <br>
     * It's used when rendering the text layout for filling background highlights of the view.
     *
     * @param length Total number of characters for which the allocation is computed.
     * @param alloc Allocation given by a parent view.
     * @return
     */
    public static Shape getRealAlloc(TextLayout textLayout, Rectangle2D textLayoutRect,
            TextHitInfo startHit, TextHitInfo endHit)
    {
        // Quick-fix to eliminate missing line in rendering italic "d" - more elaborate fix is needed
        textLayoutRect = new Rectangle2D.Double(textLayoutRect.getX(), textLayoutRect.getY(),
                textLayoutRect.getWidth() + 2, textLayoutRect.getHeight());
        Rectangle2D.Double zeroBasedRect = ViewUtils.shape2Bounds(textLayoutRect);
        zeroBasedRect.x = 0;
        zeroBasedRect.y = 0;
        Shape ret = textLayout.getVisualHighlightShape(startHit, endHit, zeroBasedRect);
        AffineTransform transform = AffineTransform.getTranslateInstance(
                textLayoutRect.getX(),
                textLayoutRect.getY()
        );
        ret = transform.createTransformedShape(ret);
        // The following gives bad result for some reason (works for layout but not for caret modelToView())
//        Shape ret2 = textLayout.getVisualHighlightShape(startHit.getCharIndex(), endHit.getCharIndex(), textLayoutRect);
        return ret;
    }
项目:incubator-netbeans    文件:HighlightsView.java   
TextLayout createPartTextLayout(int shift, int length) {
    checkTextLayoutValid();
    if (breakInfo == null) {
        breakInfo = new TextLayoutBreakInfo(textLayout.getCharacterCount());
    }
    TextLayout partTextLayout = breakInfo.findPartTextLayout(shift, length);
    if (partTextLayout == null) {
        DocumentView docView = getDocumentView();
        Document doc = docView.getDocument();
        CharSequence docText = DocumentUtilities.getText(doc);
        int startOffset = getStartOffset();
        String text = docText.subSequence(startOffset + shift, startOffset + shift + length).toString();
        if (docView.op.isNonPrintableCharactersVisible()) {
            text = text.replace(' ', DocumentViewOp.PRINTING_SPACE);
        }
        AttributeSet attrs = ViewUtils.getFirstAttributes(getAttributes());
        Font font = ViewUtils.getFont(attrs, docView.op.getDefaultFont());
        partTextLayout = docView.op.createTextLayout(text, font);
        breakInfo.add(shift, length, partTextLayout);
    }
    return partTextLayout;
}
项目:incubator-netbeans    文件:HighlightsViewUtils.java   
static Shape indexToView(TextLayout textLayout, Rectangle2D textLayoutBounds,
            int index, Position.Bias bias, int maxIndex, Shape alloc)
   {
       if (textLayout == null) {
           return alloc; // Leave given bounds
       }
       assert (maxIndex <= textLayout.getCharacterCount()) : "textLayout.getCharacterCount()=" + // NOI18N
               textLayout.getCharacterCount() + " < maxIndex=" + maxIndex; // NOI18N
       // If offset is >getEndOffset() use view-end-offset - otherwise it would throw exception from textLayout.getCaretInfo()
int charIndex = Math.min(index, maxIndex);
       // When e.g. creating fold-preview the offset can be < startOffset
       charIndex = Math.max(charIndex, 0);
       TextHitInfo startHit;
       TextHitInfo endHit;
       if (bias == Position.Bias.Forward) {
           startHit = TextHitInfo.leading(charIndex);
       } else { // backward bias
           startHit = TextHitInfo.trailing(charIndex - 1);
       }
       endHit = (charIndex < maxIndex) ? TextHitInfo.trailing(charIndex) : startHit;
       if (textLayoutBounds == null) {
           textLayoutBounds = ViewUtils.shapeAsRect(alloc);
       }
       return TextLayoutUtils.getRealAlloc(textLayout, textLayoutBounds, startHit, endHit);
   }
项目:incubator-netbeans    文件:SkipLinesViewFactory.java   
private TextLayout getTextLayout() {
    if (collapsedTextLayout == null) {
        EditorView.Parent parent = (EditorView.Parent) getParent();
        ViewRenderContext context = parent.getViewRenderContext();
        FontRenderContext frc = context.getFontRenderContext();
        assert (frc != null) : "Null FontRenderContext"; // NOI18N
        Font font = context.getRenderFont(component.getFont());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < indent; i++) {
            sb.append(' ');
        }
        sb.append("...");
        String text = sb.toString();
        collapsedTextLayout = new TextLayout(text, font, frc);
    }
    return collapsedTextLayout;
}
项目:openjdk-jdk10    文件:TextMeasureTests.java   
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);
    }
}
项目:openjdk-jdk10    文件:TextLayoutEqualsTest.java   
public static void main(String args[]) {

        Font font = new Font(Font.DIALOG, Font.PLAIN, 12);
        String text = "hello world";
        FontRenderContext frc = new FontRenderContext(null, false, false);
        TextLayout tl1 = new TextLayout(text, font, frc);
        TextLayout tl2 = new TextLayout(text, font, frc);
        if (tl1.equals(tl2) ||
            tl2.equals(tl1) ||
            tl1.equals((Object)tl2) ||
            tl2.equals((Object)tl1))
        {
             throw new RuntimeException("Equal TextLayouts");
        }
        if (!tl1.equals(tl1) ||
            !tl1.equals((Object)tl1))
        {
             throw new RuntimeException("Non-Equal TextLayouts");
        }
    }
项目:pdfbox-graphics2d    文件:PdfBoxGraphics2D.java   
private void drawStringUsingShapes(AttributedCharacterIterator iterator, float x, float y) {
    Stroke originalStroke = stroke;
    Paint originalPaint = paint;
    TextLayout textLayout = new TextLayout(iterator, getFontRenderContext());
    textLayout.draw(this, x, y);
    paint = originalPaint;
    stroke = originalStroke;
}
项目:FreeCol    文件:FreeColToolTipUI.java   
@Override
public Dimension getPreferredSize(JComponent c) {
    String tipText = ((JToolTip)c).getTipText();
    if (tipText == null || tipText.isEmpty()) {
        return new Dimension(0, 0);
    }

    float x = 0f;
    float y = 0f;
    for (String line : lineBreak.split(tipText)) {
        if (line.isEmpty()) {
            y += LEADING;
            continue;
        }
        AttributedCharacterIterator styledText
            = new AttributedString(line).getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            x = Math.max(x, layout.getVisibleAdvance());
            y += layout.getAscent() + layout.getDescent() + layout.getLeading();

        }
    }
    return new Dimension((int) (x + 2 * margin),
                         (int) (y + 2 * margin));

}
项目:OpenJSharp    文件:TextMeasureTests.java   
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);
    }
}
项目:OpenJSharp    文件:TextMeasureTests.java   
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);
    }
}
项目:jdk8u-jdk    文件:CompositionArea.java   
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());
}
项目:OpenJSharp    文件:CompositionArea.java   
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());
}
项目:jdk8u-jdk    文件:TextMeasureTests.java   
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);
    }
}
项目:litiengine    文件:SpeechBubble.java   
@Override
public void render(final Graphics2D g) {
  if (this.displayedText == null || this.displayedText.isEmpty() || !Game.getRenderEngine().canRender(this.entity)) {
    return;
  }

  final Point2D location = Game.getCamera().getViewPortLocation(this.entity);
  RenderEngine.renderImage(g, this.bubble, new Point2D.Double(location.getX() + this.entity.getWidth() / 2.0 - this.textBoxWidth / 2.0 - PADDING, location.getY() - this.height - PADDING));

  g.setColor(SPEAK_FONT_COLOR);
  final FontRenderContext frc = g.getFontRenderContext();

  final String text = this.displayedText;
  final AttributedString styledText = new AttributedString(text);
  styledText.addAttribute(TextAttribute.FONT, this.font);
  final AttributedCharacterIterator iterator = styledText.getIterator();
  final LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);
  measurer.setPosition(0);
  final float x = (float) Game.getCamera().getViewPortLocation(this.entity).getX() + this.entity.getWidth() / 2.0f - this.textBoxWidth / 2.0f;
  float y = (float) Game.getCamera().getViewPortLocation(this.entity).getY() - this.height;
  while (measurer.getPosition() < text.length()) {
    final TextLayout layout = measurer.nextLayout(this.textBoxWidth);

    y += layout.getAscent();
    final float dx = layout.isLeftToRight() ? 0 : this.textBoxWidth - layout.getAdvance();
    layout.draw(g, x + dx, y);
    y += layout.getDescent() + layout.getLeading();
  }
}
项目:Logisim    文件:EditableLabel.java   
private void computeDimensions(Graphics g, Font font, FontMetrics fm) {
    String s = text;
    FontRenderContext frc = ((Graphics2D) g).getFontRenderContext();
    width = fm.stringWidth(s);
    ascent = fm.getAscent();
    descent = fm.getDescent();
    int[] xs = new int[s.length()];
    int[] ys = new int[s.length()];
    for (int i = 0; i < xs.length; i++) {
        xs[i] = fm.stringWidth(s.substring(0, i + 1));
        TextLayout lay = new TextLayout(s.substring(i, i + 1), font, frc);
        Rectangle2D rect = lay.getBounds();
        int asc = (int) Math.ceil(-rect.getMinY());
        int desc = (int) Math.ceil(rect.getMaxY());
        if (asc < 0)
            asc = 0;
        if (asc > 0xFFFF)
            asc = 0xFFFF;
        if (desc < 0)
            desc = 0;
        if (desc > 0xFFFF)
            desc = 0xFFFF;
        ys[i] = (asc << 16) | desc;
    }
    charX = xs;
    charY = ys;
    dimsKnown = true;
}
项目:jdk8u-jdk    文件:PathGraphics.java   
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);
}
项目:incubator-netbeans    文件:FoldView.java   
static TextHitInfo x2RelOffset(TextLayout textLayout, float x) {
    TextHitInfo hit;
    x -= EXTRA_MARGIN_WIDTH;
    if (x >= textLayout.getAdvance()) {
        hit = TextHitInfo.trailing(textLayout.getCharacterCount());
    } else {
        hit = textLayout.hitTestChar(x, 0); // What about backward bias -> with higher offsets it may go back visually
    }
    return hit;

}
项目:incubator-netbeans    文件:DrawGraphics.java   
private static void drawStringTextLayout(JComponent c, Graphics g, String text, int x, int baselineY) {
    if (!(g instanceof Graphics2D)) {
        g.drawString(text, x, baselineY);
    } else { // Graphics2D available
        Graphics2D g2d = (Graphics2D)g;
        FontRenderContext frc = g2d.getFontRenderContext();
        TextLayout layout = new TextLayout(text, g2d.getFont(), frc);
        layout.draw(g2d, x, baselineY);
    }
}
项目:incubator-netbeans    文件:GlyphGutter.java   
protected int getLineNumberWidth() {
    int newWidth = 0;
    EditorUI eui = editorUI;
    if (eui != null) {
        /*
        Insets insets = eui.getLineNumberMargin();
        if (insets != null) {
            newWidth += insets.left + insets.right;
        }
         */
        JTextComponent tc = eui.getComponent();
        if (font != null && tc != null) {
            Graphics g;
            FontRenderContext frc;
            FontMetrics fm;
            if ((g = tc.getGraphics()) != null && (g instanceof Graphics2D) &&
                (frc = ((Graphics2D)g).getFontRenderContext()) != null)
            {
                newWidth += new TextLayout(String.valueOf(highestLineNumber), font, frc).getAdvance();
            } else if ((fm = getFontMetrics(font)) != null) {
                // Use FontMetrics.stringWidth() as best approximation
                newWidth += fm.stringWidth(String.valueOf(highestLineNumber));
            }
        }
    }

    return newWidth;
}
项目:jdk8u-jdk    文件:SunGraphics2D.java   
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();
    }
}
项目:jdk8u-jdk    文件:TextMeasureTests.java   
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);
}
项目:incubator-netbeans    文件:FontInfo.java   
FontInfo(Font origFont, JTextComponent textComponent, FontRenderContext frc, float rowHeightCorrection, int textZoom) {
    renderFont = (textZoom != 0)
            ? new Font(origFont.getName(), origFont.getStyle(), Math.max(origFont.getSize() + textZoom, 1))
            : origFont;
    char defaultChar = 'A';
    String defaultCharText = String.valueOf(defaultChar);
    TextLayout defaultCharTextLayout = new TextLayout(defaultCharText, renderFont, frc); // NOI18N
    TextLayout rowHeightTextLayout = new TextLayout("A_|B", renderFont, frc);
    // Round the ascent to eliminate long mantissa without any visible effect on rendering.
    updateRowHeight(rowHeightTextLayout, rowHeightCorrection);
    // Ceil fractions to whole numbers since this measure may be used for background rendering
    charWidth = (float) Math.ceil(defaultCharTextLayout.getAdvance());
    LineMetrics lineMetrics = renderFont.getLineMetrics(defaultCharText, frc);
    underlineAndStrike[0] = lineMetrics.getUnderlineOffset() * rowHeightCorrection;
    underlineAndStrike[1] = lineMetrics.getUnderlineThickness();
    underlineAndStrike[2] = lineMetrics.getStrikethroughOffset() * rowHeightCorrection;
    underlineAndStrike[3] = lineMetrics.getStrikethroughThickness();
    if (LOG.isLoggable(Level.FINE)) {
        FontMetrics fm = textComponent.getFontMetrics(origFont); // From original font
        LOG.fine("Orig Font=" + origFont + // NOI18N
                "\n  " + this + ", charWidth=" + charWidth + ", textZoom=" + textZoom + // NOI18N
                "\n  rowHeightCorrection=" + rowHeightCorrection + // NOI18N
                ", underlineO/T=" + underlineAndStrike[0] + "/" + underlineAndStrike[1] + // NOI18N
                ", strikethroughO/T=" + underlineAndStrike[2] + "/" + underlineAndStrike[3] + // NOI18N
                "\n  FontMetrics (for comparison; without-RHC): fm-line-height=" + fm.getHeight() + // NOI18N
                ", fm-ascent,descent,leading=" + fm.getAscent() + "," + fm.getDescent() + "," + fm.getLeading() + // NOI18N
                "\n"); // NOI18N
        if (LOG.isLoggable(Level.FINEST)) {
            LOG.log(Level.FINEST, "FontInfo creation stacktrace", new Exception()); // NOI18N
        }
    }
}
项目:openjdk-jdk10    文件:OutlineTextRenderer.java   
public void drawString(SunGraphics2D g2d, String str, double x, double y) {

        if ("".equals(str)) {
            return; // TextLayout constructor throws IAE on "".
        }
        TextLayout tl = new TextLayout(str, g2d.getFont(),
                                       g2d.getFontRenderContext());
        Shape s = tl.getOutline(AffineTransform.getTranslateInstance(x, y));

        int textAAHint = g2d.getFontInfo().aaHint;

        int prevaaHint = - 1;
        if (textAAHint != SunHints.INTVAL_TEXT_ANTIALIAS_OFF &&
            g2d.antialiasHint != SunHints.INTVAL_ANTIALIAS_ON) {
            prevaaHint = g2d.antialiasHint;
            g2d.antialiasHint =  SunHints.INTVAL_ANTIALIAS_ON;
            g2d.validatePipe();
        } else if (textAAHint == SunHints.INTVAL_TEXT_ANTIALIAS_OFF
            && g2d.antialiasHint != SunHints.INTVAL_ANTIALIAS_OFF) {
            prevaaHint = g2d.antialiasHint;
            g2d.antialiasHint =  SunHints.INTVAL_ANTIALIAS_OFF;
            g2d.validatePipe();
        }

        g2d.fill(s);

        if (prevaaHint != -1) {
             g2d.antialiasHint = prevaaHint;
             g2d.validatePipe();
        }
    }
项目:jdk8u-jdk    文件:GlyphListPipe.java   
public void drawChars(SunGraphics2D sg2d,
                      char data[], int offset, int length,
                      int ix, int iy)
{
    FontInfo info = sg2d.getFontInfo();
    float x, y;
    if (info.pixelHeight > OutlineTextRenderer.THRESHHOLD) {
        SurfaceData.outlineTextRenderer.drawChars(
                                    sg2d, data, offset, length, ix, iy);
        return;
    }
    if (sg2d.transformState >= SunGraphics2D.TRANSFORM_TRANSLATESCALE) {
        double origin[] = {ix + info.originX, iy + info.originY};
        sg2d.transform.transform(origin, 0, origin, 0, 1);
        x = (float) origin[0];
        y = (float) origin[1];
    } else {
        x = ix + info.originX + sg2d.transX;
        y = iy + info.originY + sg2d.transY;
    }
    GlyphList gl = GlyphList.getInstance();
    if (gl.setFromChars(info, data, offset, length, x, y)) {
        drawGlyphList(sg2d, gl);
        gl.dispose();
    } else {
        gl.dispose(); // release this asap.
        TextLayout tl = new TextLayout(new String(data, offset, length),
                                       sg2d.getFont(),
                                       sg2d.getFontRenderContext());
        tl.draw(sg2d, ix, iy);

    }
}
项目:incubator-netbeans    文件:DocumentViewOp.java   
/**
 * Get width available for display of child views. For non-wrap case it's Integer.MAX_VALUE
 * and for wrapping it's a display width or (if display width would become too narrow)
 * a width of four chars to not overflow the word wrapping algorithm.
 * @return 
 */
float getAvailableWidth() {
    if (!isAnyStatusBit(AVAILABLE_WIDTH_VALID)) {
        // Mark valid and assign early values to prevent stack overflow in getLineContinuationCharTextLayout()
        setStatusBits(AVAILABLE_WIDTH_VALID);
        availableWidth = Integer.MAX_VALUE;
        renderWrapWidth = availableWidth;
        TextLayout lineContTextLayout = getLineContinuationCharTextLayout();
        if (lineContTextLayout != null && (getLineWrapType() != LineWrapType.NONE)) {
            availableWidth = Math.max(getVisibleRect().width, 4 * getDefaultCharWidth() + lineContTextLayout.getAdvance());
            renderWrapWidth = availableWidth - lineContTextLayout.getAdvance();
        }
    }
    return availableWidth;
}
项目:openjdk-jdk10    文件:TextMeasureTests.java   
public void runTest(Object ctx, int numReps) {
    TLContext tlctx = (TLContext)ctx;
    TextLayout tl = tlctx.tl;
    Rectangle2D r;
    do {
        r = tl.getBounds();
    } while (--numReps >= 0);
}
项目:jdk8u-jdk    文件:Font.java   
/**
 * 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());
    }
}
项目:openjdk-jdk10    文件:PathGraphics.java   
protected void drawString(String str, float x, float y,
                          Font font, FontRenderContext frc, float w) {
    TextLayout layout =
        new TextLayout(str, font, frc);
    Shape textShape =
        layout.getOutline(AffineTransform.getTranslateInstance(x, y));
    fill(textShape);
}
项目:jdk8u-jdk    文件:SunGraphics2D.java   
public void drawChars(char data[], int offset, int length, int x, int y) {

        if (data == null) {
            throw new NullPointerException("char data is null");
        }
        if (offset < 0 || length < 0 || offset + length > data.length) {
            throw new ArrayIndexOutOfBoundsException("bad offset/length");
        }
        if (font.hasLayoutAttributes()) {
            if (data.length == 0) {
                return;
            }
            new TextLayout(new String(data, offset, length),
                           font, getFontRenderContext()).draw(this, x, y);
            return;
        }

        try {
            textpipe.drawChars(this, data, offset, length, x, y);
        } catch (InvalidPipeException e) {
            try {
                revalidateAll();
                textpipe.drawChars(this, data, offset, length, 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();
        }
    }
项目:incubator-netbeans    文件:HighlightsView.java   
@Override
protected StringBuilder appendViewInfo(StringBuilder sb, int indent, String xyInfo, int importantChildIndex) {
    super.appendViewInfo(sb, indent, xyInfo, importantChildIndex);
    sb.append(" TL=");
    if (textLayout == null) {
        sb.append("<NULL>");
    } else {
        sb.append(TextLayoutUtils.toStringShort((TextLayout) textLayout));
    }
    return sb;
}
项目:incubator-netbeans    文件:HighlightsViewUtils.java   
static int viewToIndex(TextLayout textLayout, double x, Shape alloc, Position.Bias[] biasReturn) {
    Rectangle2D bounds = ViewUtils.shapeAsRect(alloc);
    TextHitInfo hitInfo = x2Index(textLayout, (float)(x - bounds.getX()));
    if (biasReturn != null) {
        biasReturn[0] = hitInfo.isLeadingEdge() ? Position.Bias.Forward : Position.Bias.Backward;
    }
    return hitInfo.getInsertionIndex();
}
项目:jdk8u-jdk    文件:TextMeasureTests.java   
public void runTest(Object ctx, int numReps) {
    TLExContext tlctx = (TLExContext)ctx;
    TextLayout tl = tlctx.tl;
    int numhits = tlctx.hits.length;
    Rectangle2D lb = tlctx.lb;
    TextHitInfo hit;
    for (int i = 0; i <= numhits; ++i) {
        float x = (float)(lb.getMinX() + lb.getWidth() * i / numhits);
        float y = (float)(lb.getMinY() + lb.getHeight() * i / numhits);
        hit = tl.hitTestChar(x, y, lb);
    }
}
项目:openjdk-jdk10    文件:GlyphVectorOutline.java   
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);
}
项目:incubator-netbeans    文件:SkipLinesViewFactory.java   
@Override
public void paint(Graphics2D g, Shape alloc, Rectangle clipBounds) {
    Rectangle2D.Double allocBounds = ViewUtils.shape2Bounds(alloc);
    TextLayout textLayout = getTextLayout();
    if (textLayout != null) {
        g.setColor(component.getForeground());
        EditorView.Parent parent = (EditorView.Parent) getParent();
        float ascent = parent.getViewRenderContext().getDefaultAscent();
        float x = (float) allocBounds.getX();
        float y = (float) allocBounds.getY();
        textLayout.draw(g, x, y + ascent);
    }
}
项目:incubator-netbeans    文件:SkipLinesViewFactory.java   
@Override
public float getPreferredSpan(int axis) {
    EditorView.Parent parent = (EditorView.Parent) getParent();
    if (axis == View.X_AXIS) {
        float advance = 0;
        TextLayout textLayout = getTextLayout();
        if (textLayout == null) {
            return 0f;
        }
        return textLayout.getAdvance();
    } else {
        return (parent != null) ? parent.getViewRenderContext().getDefaultRowHeight() : 0f;
    }
}
项目:jdk8u-jdk    文件:CompositionArea.java   
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();
    }
}