Example usage for java.text AttributedString AttributedString

List of usage examples for java.text AttributedString AttributedString

Introduction

In this page you can find the example usage for java.text AttributedString AttributedString.

Prototype

public AttributedString(String text, Map<? extends Attribute, ?> attributes) 

Source Link

Document

Constructs an AttributedString instance with the given text and attributes.

Usage

From source file:MainClass.java

public void paint(Graphics g) {
    Dimension size = getSize();//from   w ww . j  a  v a 2s  .c  om

    String s = "To java2s.com or not to java2s.com, that is a question";

    Hashtable map = new Hashtable();
    map.put(TextAttribute.SIZE, new Float(32.0f));

    AttributedString as = new AttributedString(s, map);

    map = new Hashtable();
    map.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);

    as.addAttributes(map, 33, 52);

    AttributedCharacterIterator aci = as.getIterator();

    int startIndex = aci.getBeginIndex();
    int endIndex = aci.getEndIndex();

    LineBreakMeasurer measurer;
    measurer = new LineBreakMeasurer(aci, new FontRenderContext(null, false, false));
    measurer.setPosition(startIndex);

    float wrappingWidth = (float) size.width;

    float Y = 0.0f;

    while (measurer.getPosition() < endIndex) {
        TextLayout layout = measurer.nextLayout(wrappingWidth);

        Y += layout.getAscent();

        float X = 0.0f;

        switch (justify) {
        case LEFT:
            if (layout.isLeftToRight())
                X = 0.0f;
            else
                X = wrappingWidth - layout.getAdvance();
            break;

        case RIGHT:
            if (layout.isLeftToRight())
                X = wrappingWidth - layout.getVisibleAdvance();
            else
                X = wrappingWidth;
            break;

        case CENTER:
            if (layout.isLeftToRight())
                X = (wrappingWidth - layout.getVisibleAdvance()) / 2;
            else
                X = (wrappingWidth + layout.getAdvance()) / 2 - layout.getAdvance();
            break;

        case EQUALITY:
            layout = layout.getJustifiedLayout(wrappingWidth);
        }

        layout.draw((Graphics2D) g, X, Y);

        Y += layout.getDescent() + layout.getLeading();
    }
}

From source file:Utils.java

/** 
 * Renders a paragraph of text (line breaks ignored) to an image (created and returned). 
 *
 * @param font The font to use/*from www. j a v a 2s.co  m*/
 * @param textColor The color of the text
 * @param text The message
 * @param width The width the text should be limited to
 * @return An image with the text rendered into it
 */
public static BufferedImage renderTextToImage(Font font, Color textColor, String text, int width) {
    Hashtable map = new Hashtable();
    map.put(TextAttribute.FONT, font);
    AttributedString attributedString = new AttributedString(text, map);
    AttributedCharacterIterator paragraph = attributedString.getIterator();

    FontRenderContext frc = new FontRenderContext(null, false, false);
    int paragraphStart = paragraph.getBeginIndex();
    int paragraphEnd = paragraph.getEndIndex();
    LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);

    float drawPosY = 0;

    //First time around, just determine the height
    while (lineMeasurer.getPosition() < paragraphEnd) {
        TextLayout layout = lineMeasurer.nextLayout(width);

        // Move it down
        drawPosY += layout.getAscent() + layout.getDescent() + layout.getLeading();
    }

    BufferedImage image = createCompatibleImage(width, (int) drawPosY);
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    drawPosY = 0;
    lineMeasurer.setPosition(paragraphStart);
    while (lineMeasurer.getPosition() < paragraphEnd) {
        TextLayout layout = lineMeasurer.nextLayout(width);

        // Move y-coordinate by the ascent of the layout.
        drawPosY += layout.getAscent();

        /* Compute pen x position.  If the paragraph is
           right-to-left, we want to align the TextLayouts
           to the right edge of the panel.
         */
        float drawPosX;
        if (layout.isLeftToRight()) {
            drawPosX = 0;
        } else {
            drawPosX = width - layout.getAdvance();
        }

        // Draw the TextLayout at (drawPosX, drawPosY).
        layout.draw(graphics, drawPosX, drawPosY);

        // Move y-coordinate in preparation for next layout.
        drawPosY += layout.getDescent() + layout.getLeading();
    }

    graphics.dispose();
    return image;
}

From source file:com.qumasoft.guitools.compare.ContentRow.java

@Override
public void paint(Graphics g) {
    if ((getRowType() == ROWTYPE_REPLACE) && rowHadAnnotations) {
        Graphics2D g2 = (Graphics2D) g;

        String s = getText();/*  w  w  w.  j  av  a  2 s  .c o m*/

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        if (s.length() > 0) {
            int index = 0;
            AttributedString attributedString = new AttributedString(s, getFont().getAttributes());
            try {
                for (byte rType : fileACharacterTypeArray) {
                    switch (rType) {
                    case ContentRow.ROWTYPE_DELETE:
                        attributedString.addAttribute(TextAttribute.STRIKETHROUGH, null, index, index + 1);
                        break;
                    case ContentRow.ROWTYPE_REPLACE:
                        attributedString.addAttribute(TextAttribute.BACKGROUND,
                                ColorManager.getReplaceCompareHiliteBackgroundColor(), index, index + 1);
                        break;
                    default:
                        break;
                    }
                    index++;
                }
                g2.drawString(attributedString.getIterator(), 0, getFont().getSize());
            } catch (java.lang.IllegalArgumentException e) {
                LOGGER.log(Level.WARNING, "bad replace indexes. begin index: [" + index + "] end index: ["
                        + index + "]. String length: [" + s.length() + "]");
            }
        } else {
            super.paint(g);
        }
    } else {
        super.paint(g);
    }
}

From source file:com.pronoiahealth.olhie.server.services.BookCoverImageService.java

/**
 * Create an image that contains text//from  w w  w  .  j  a v  a2s.c om
 * 
 * @param height
 * @param width
 * @param text
 * @param textColor
 * @param center
 * @param fontMap
 * @param type
 * @return
 */
private BufferedImage createText(int height, int width, String text, String textColor, boolean center,
        Map<TextAttribute, Object> fontMap, int type) {
    BufferedImage img = new BufferedImage(width, height, type);
    Graphics2D g2d = null;
    try {
        g2d = (Graphics2D) img.getGraphics();

        // Create attributed text
        AttributedString txt = new AttributedString(text, fontMap);

        // Set graphics color
        g2d.setColor(Color.decode(textColor));

        // Create a new LineBreakMeasurer from the paragraph.
        // It will be cached and re-used.
        AttributedCharacterIterator paragraph = txt.getIterator();
        int paragraphStart = paragraph.getBeginIndex();
        int paragraphEnd = paragraph.getEndIndex();
        FontRenderContext frc = g2d.getFontRenderContext();
        LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(paragraph, frc);

        // Set break width to width of Component.
        float breakWidth = (float) width;
        float drawPosY = 0;
        // Set position to the index of the first character in the
        // paragraph.
        lineMeasurer.setPosition(paragraphStart);

        // Get lines until the entire paragraph has been displayed.
        while (lineMeasurer.getPosition() < paragraphEnd) {
            // Retrieve next layout. A cleverer program would also cache
            // these layouts until the component is re-sized.
            TextLayout layout = lineMeasurer.nextLayout(breakWidth);

            // Compute pen x position. If the paragraph is right-to-left we
            // will align the TextLayouts to the right edge of the panel.
            // Note: drawPosX is always where the LEFT of the text is
            // placed.
            float drawPosX = layout.isLeftToRight() ? 0 : breakWidth - layout.getAdvance();

            if (center == true) {
                double xOffSet = (width - layout.getBounds().getWidth()) / 2;
                drawPosX = drawPosX + new Float(xOffSet);
            }

            // Move y-coordinate by the ascent of the layout.
            drawPosY += layout.getAscent();

            // Draw the TextLayout at (drawPosX, drawPosY).
            layout.draw(g2d, drawPosX, drawPosY);

            // Move y-coordinate in preparation for next layout.
            drawPosY += layout.getDescent() + layout.getLeading();
        }
    } finally {
        if (g2d != null) {
            g2d.dispose();
        }
    }
    return img;
}

From source file:net.sf.jasperreports.engine.fill.SimpleTextLineWrapper.java

protected int measureExactLineBreakIndex(float width, int endLimit, boolean requireWord) {
    //FIXME would it be faster to create and cache a LineBreakMeasurer for the whole paragraph?
    Map<Attribute, Object> attributes = new HashMap<Attribute, Object>();
    // we only need the font as it includes the size and style
    attributes.put(TextAttribute.FONT, fontInfo.fontInfo.font);

    String textLine = paragraphText.substring(paragraphPosition, endLimit);
    AttributedString attributedLine = new AttributedString(textLine, attributes);

    // we need a fresh iterator for the line
    BreakIterator breakIterator = paragraphTruncateAtChar ? BreakIterator.getCharacterInstance()
            : BreakIterator.getLineInstance();
    LineBreakMeasurer breakMeasurer = new LineBreakMeasurer(attributedLine.getIterator(), breakIterator,
            context.getFontRenderContext());
    int breakIndex = breakMeasurer.nextOffset(width, endLimit - paragraphPosition, requireWord)
            + paragraphPosition;//from   w  w w.ja  v  a2  s . co  m
    if (logTrace) {
        log.trace("exact line break index measured at " + (paragraphOffset + breakIndex));
    }

    return breakIndex;
}