List of usage examples for java.awt.font TextLayout getDescent
public float getDescent()
From source file:TextFormat.java
public void paint(Graphics g) { if (text == null || text.length() == 0) return;//w ww .ja v a2 s . com if (layouts == null) getLayouts(g); Point pen = new Point(0, 0); Graphics2D g2d = (Graphics2D) g; g2d.setColor(java.awt.Color.black); // or a property g2d.setFont(font); Iterator it = layouts.iterator(); while (it.hasNext()) { TextLayout layout = (TextLayout) it.next(); pen.y += (layout.getAscent()); g2d.setFont(font); layout.draw(g2d, pen.x, pen.y); pen.y += layout.getDescent(); //pen.y += leading; } }
From source file:LineBreakSample.java
public void paintComponent(Graphics g) { super.paintComponent(g); setBackground(Color.white);//w w w. j av a2s .c om Graphics2D graphics2D = (Graphics2D) g; // Set formatting width to width of Component. Dimension size = getSize(); float formatWidth = (float) size.width; float drawPosY = 0; lineMeasurer.setPosition(paragraphStart); // Get lines from lineMeasurer until the entire // paragraph has been displayed. while (lineMeasurer.getPosition() < paragraphEnd) { // Retrieve next layout. TextLayout layout = lineMeasurer.nextLayout(formatWidth); // 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 = formatWidth - layout.getAdvance(); } // Draw the TextLayout at (drawPosX, drawPosY). layout.draw(graphics2D, drawPosX, drawPosY); // Move y-coordinate in preparation for next layout. drawPosY += layout.getDescent() + layout.getLeading(); } }
From source file:forge.view.arcane.util.OutlinedLabel.java
/** {@inheritDoc} */ @Override// w w w .j av a 2 s . c om public final void paint(final Graphics g) { if (getText().length() == 0) { return; } Dimension size = getSize(); // // if( size.width < 50 ) { // g.setColor(Color.cyan); // g.drawRect(0, 0, size.width-1, size.height-1); // } Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); int textX = outlineSize, textY = 0; int wrapWidth = Math.max(0, wrap ? size.width - outlineSize * 2 : Integer.MAX_VALUE); final String text = getText(); AttributedString attributedString = new AttributedString(text); if (!StringUtils.isEmpty(text)) { attributedString.addAttribute(TextAttribute.FONT, getFont()); } AttributedCharacterIterator charIterator = attributedString.getIterator(); FontRenderContext fontContext = g2d.getFontRenderContext(); LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, BreakIterator.getWordInstance(Locale.ENGLISH), fontContext); int lineCount = 0; while (measurer.getPosition() < charIterator.getEndIndex()) { measurer.nextLayout(wrapWidth); lineCount++; if (lineCount > 2) { break; } } charIterator.first(); // Use char wrap if word wrap would cause more than two lines of text. if (lineCount > 2) { measurer = new LineBreakMeasurer(charIterator, BreakIterator.getCharacterInstance(Locale.ENGLISH), fontContext); } else { measurer.setPosition(0); } while (measurer.getPosition() < charIterator.getEndIndex()) { TextLayout textLayout = measurer.nextLayout(wrapWidth); float ascent = textLayout.getAscent(); textY += ascent; // Move down to baseline. g2d.setColor(outlineColor); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f)); textLayout.draw(g2d, textX + outlineSize, textY - outlineSize); textLayout.draw(g2d, textX + outlineSize, textY + outlineSize); textLayout.draw(g2d, textX - outlineSize, textY - outlineSize); textLayout.draw(g2d, textX - outlineSize, textY + outlineSize); g2d.setColor(getForeground()); g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f)); textLayout.draw(g2d, textX, textY); // Move down to top of next line. textY += textLayout.getDescent() + textLayout.getLeading(); } }
From source file:MainClass.java
public void paint(Graphics g) { Dimension size = getSize();/* w w w.ja v a 2 s . c o m*/ 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:com.lfv.lanzius.server.WorkspaceView.java
@Override protected void paintComponent(Graphics g) { int w = getWidth(); int h = getHeight(); Document doc = server.getDocument(); Color storedCol = g.getColor(); Font storedFont = g.getFont(); // Fill workspace area g.setColor(getBackground());/*from w ww . j a v a 2 s . c o m*/ g.fillRect(0, 0, w, h); // Should the cached version be updated? int updateDocumentVersion = server.getDocumentVersion(); boolean update = (documentVersion != updateDocumentVersion); // Check if we have cached the latest document version, otherwise cache the terminals if (update) { log.debug("Updating view to version " + updateDocumentVersion); terminalMap.clear(); groupList.clear(); if (doc != null) { synchronized (doc) { // Clear the visible attribute on all groups // except the started or paused ones Element egd = doc.getRootElement().getChild("GroupDefs"); Iterator iter = egd.getChildren().iterator(); while (iter.hasNext()) { Element eg = (Element) iter.next(); boolean isVisible = !DomTools.getAttributeString(eg, "state", "stopped", false) .equals("stopped"); eg.setAttribute("visible", String.valueOf(isVisible)); } // Gather information about terminals and cache it Element etd = doc.getRootElement().getChild("TerminalDefs"); iter = etd.getChildren().iterator(); while (iter.hasNext()) { Element et = (Element) iter.next(); int tid = DomTools.getAttributeInt(et, "id", 0, false); if (tid > 0) { // Create terminal and add it to list Terminal t = new Terminal(tid, DomTools.getAttributeInt(et, "x", 0, false), DomTools.getAttributeInt(et, "y", 0, false), DomTools.getChildText(et, "Name", "T/" + tid, false), DomTools.getAttributeBoolean(et, "online", false, false), DomTools.getAttributeBoolean(et, "selected", false, false)); terminalMap.put(tid, t); // Is the terminal monitored? t.isMonitored = DomTools.getAttributeBoolean(et, "monitored", false, false); // Examine the Player element under PlayerSetup t.groupColor = null; Element ep = DomTools.getElementFromSection(doc, "PlayerSetup", "terminalid", String.valueOf(tid)); // Has linked player for this terminal if (ep != null) { StringBuffer sb = new StringBuffer(); // Append player name sb.append(DomTools.getChildText(ep, "Name", "P/?", true)); sb.append(" ("); // Append role list boolean hasRoles = false; Element ers = ep.getChild("RoleSetup"); if (ers != null) { Iterator iterr = ers.getChildren().iterator(); while (iterr.hasNext()) { Element er = (Element) iterr.next(); String id = er.getAttributeValue("id"); er = DomTools.getElementFromSection(doc, "RoleDefs", "id", id); if (er != null) { sb.append(DomTools.getChildText(er, "Name", "R/" + id, false)); sb.append(", "); hasRoles = true; } } if (hasRoles) { // Trim last comma int len = sb.length(); sb.setLength(Math.max(len - 2, 0)); } sb.append(")"); } t.roles = sb.toString(); // Is the player relocated? t.isRelocated = DomTools.getAttributeBoolean(ep, "relocated", false, false); // Get group name and color Element eg = DomTools.getElementFromSection(doc, "GroupDefs", "id", DomTools.getAttributeString(ep, "groupid", "0", true)); t.groupColor = Color.lightGray; if (eg != null) { String sc = DomTools.getChildText(eg, "Color", null, false); if (sc != null) { try { t.groupColor = Color.decode(sc); } catch (NumberFormatException ex) { log.warn("Invalid color attribute on Group node, defaulting to grey"); } } //t.name += " "+DomTools.getChildText(eg, "Name", "G/"+eg.getAttributeValue("id"), false); t.groupName = DomTools.getChildText(eg, "Name", "G/" + eg.getAttributeValue("id"), false); // This group should now be visible eg.setAttribute("visible", "true"); } else log.warn("Invalid groupid attribute on Player node, defaulting to grey"); } } else log.error("Invalid id attribute on Terminal node, skipping"); } // Gather information about groups and cache it iter = egd.getChildren().iterator(); while (iter.hasNext()) { Element eg = (Element) iter.next(); if (DomTools.getAttributeBoolean(eg, "visible", false, false)) { int gid = DomTools.getAttributeInt(eg, "id", 0, true); if (gid > 0) { Group grp = new Group(gid, DomTools.getChildText(eg, "Name", "G/" + gid, false), DomTools.getAttributeBoolean(eg, "selected", false, false)); groupList.add(grp); // group color String sc = DomTools.getChildText(eg, "Color", null, false); if (sc != null) { try { grp.color = Color.decode(sc); } catch (NumberFormatException ex) { log.warn("Invalid color attribute on Group node, defaulting to grey"); } } // state color grp.stateColor = Color.red; String state = DomTools.getAttributeString(eg, "state", "stopped", false); if (state.equals("started")) grp.stateColor = Color.green; else if (state.equals("paused")) grp.stateColor = Color.orange; } } } } } } if (doc == null) { g.setColor(Color.black); String text = "No configuration loaded. Select 'Load configuration...' from the file menu."; g.drawString(text, (w - SwingUtilities.computeStringWidth(g.getFontMetrics(), text)) / 2, h * 5 / 12); } else { g.setFont(new Font("Dialog", Font.BOLD, 13)); Iterator<Terminal> itert = terminalMap.values().iterator(); while (itert.hasNext()) { Terminal t = itert.next(); // Draw box int b = t.isSelected ? SERVERVIEW_SELECTION_BORDER : 1; g.setColor(Color.black); g.fillRect(t.x + SERVERVIEW_SELECTION_BORDER - b, t.y + SERVERVIEW_SELECTION_BORDER - b, SERVERVIEW_TERMINAL_WIDTH + 2 * b, SERVERVIEW_TERMINAL_HEIGHT + 2 * b); g.setColor(t.groupColor == null ? Color.white : t.groupColor); g.fillRect(t.x + SERVERVIEW_SELECTION_BORDER, t.y + SERVERVIEW_SELECTION_BORDER, SERVERVIEW_TERMINAL_WIDTH, SERVERVIEW_TERMINAL_HEIGHT); // Inner areas Rectangle r = new Rectangle(t.x + SERVERVIEW_SELECTION_BORDER + SERVERVIEW_TERMINAL_BORDER, t.y + SERVERVIEW_SELECTION_BORDER + SERVERVIEW_TERMINAL_BORDER, SERVERVIEW_TERMINAL_WIDTH - 2 * SERVERVIEW_TERMINAL_BORDER, g.getFontMetrics().getHeight() + 4); g.setColor(Color.white); g.fillRect(r.x, r.y, r.width, r.height); g.fillRect(r.x, r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 2, r.width, SERVERVIEW_TERMINAL_HEIGHT - 3 * SERVERVIEW_TERMINAL_BORDER - r.height - 2); g.setColor(Color.black); g.drawRect(r.x, r.y, r.width, r.height); g.drawRect(r.x, r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 2, r.width, SERVERVIEW_TERMINAL_HEIGHT - 3 * SERVERVIEW_TERMINAL_BORDER - r.height - 2); // Name of terminal and group if (server.isaClient(t.tid)) { g.drawImage(indicatorIsa.getImage(), r.x + r.width - 20, r.y + SERVERVIEW_TERMINAL_HEIGHT - 26, null); } g.drawString(t.name + " " + t.groupName, r.x + 4, r.y + r.height - 4); double px = r.x + 4; double py = r.y + r.height + SERVERVIEW_TERMINAL_BORDER + 5; // Draw monitored indicator if (t.isMonitored) { g.drawImage(indicatorMonitored.getImage(), r.x + r.width - 9, r.y + 3, null); } // Draw relocated indicator if (t.isRelocated) { g.drawImage(indicatorRelocated.getImage(), r.x + r.width - 9, r.y + 13, null); } // Draw online indicator r.setBounds(r.x, r.y + r.height, r.width, 3); g.setColor(t.isOnline ? Color.green : Color.red); g.fillRect(r.x, r.y, r.width, r.height); g.setColor(Color.black); g.drawRect(r.x, r.y, r.width, r.height); // Roles if (t.roles.length() > 0) { LineBreakMeasurer lbm = new LineBreakMeasurer(new AttributedString(t.roles).getIterator(), new FontRenderContext(null, false, true)); TextLayout layout; while ((layout = lbm .nextLayout(SERVERVIEW_TERMINAL_WIDTH - 2 * SERVERVIEW_TERMINAL_BORDER)) != null) { if (py < t.y + SERVERVIEW_TERMINAL_HEIGHT) { py += layout.getAscent(); layout.draw((Graphics2D) g, (int) px, (int) py); py += layout.getDescent() + layout.getLeading(); } } } } // Draw group indicators int nbrGroupsInRow = w / (2 * Constants.SERVERVIEW_SELECTION_BORDER + 2 + Constants.SERVERVIEW_GROUP_WIDTH); if (nbrGroupsInRow < 1) nbrGroupsInRow = 1; int nbrGroupRows = (groupList.size() + nbrGroupsInRow - 1) / nbrGroupsInRow; int innerWidth = Constants.SERVERVIEW_GROUP_WIDTH; int innerHeight = g.getFontMetrics().getHeight() + 5; int outerWidth = innerWidth + 2 * Constants.SERVERVIEW_SELECTION_BORDER + 2; int outerHeight = innerHeight + 2 * Constants.SERVERVIEW_SELECTION_BORDER + 2; int x = 0; int y = h - outerHeight * nbrGroupRows; g.setColor(Color.white); g.fillRect(0, y, w, h - y); g.setColor(Color.black); g.drawLine(0, y - 1, w - 1, y - 1); Iterator<Group> iterg = groupList.iterator(); while (iterg.hasNext()) { Group grp = iterg.next(); // Group box grp.boundingRect.setBounds(x, y, outerWidth, outerHeight); int b = grp.isSelected ? Constants.SERVERVIEW_SELECTION_BORDER : 1; g.setColor(Color.black); g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER - b + 1, y + Constants.SERVERVIEW_SELECTION_BORDER - b + 1, innerWidth + 2 * b, innerHeight + 2 * b); g.setColor(grp.color); g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER + 1, y + Constants.SERVERVIEW_SELECTION_BORDER + 1, innerWidth, innerHeight); g.setColor(Color.black); g.drawString(grp.name, x + Constants.SERVERVIEW_SELECTION_BORDER + 4, y + Constants.SERVERVIEW_SELECTION_BORDER + innerHeight - 4 + 1); // Draw started indicator g.setColor(grp.stateColor); g.fillRect(x + Constants.SERVERVIEW_SELECTION_BORDER + 1, y + Constants.SERVERVIEW_SELECTION_BORDER + 1, innerWidth, 2); g.setColor(Color.black); g.drawLine(x + Constants.SERVERVIEW_SELECTION_BORDER + 1, y + Constants.SERVERVIEW_SELECTION_BORDER + 3, x + Constants.SERVERVIEW_SELECTION_BORDER + 1 + innerWidth, y + Constants.SERVERVIEW_SELECTION_BORDER + 3); x += outerWidth; if ((x + outerWidth) > w) { x = 0; y += outerHeight; } } } // Store cached version documentVersion = updateDocumentVersion; g.setColor(storedCol); g.setFont(storedFont); }
From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java
public void drawString(Graphics g, String text, RectangularShape bounds, Align align, double angle, boolean multiline) { Graphics2D g2 = (Graphics2D) g; Font font = g2.getFont();//from w w w.j ava2s . co m if (angle != 0) { g2.setFont(font.deriveFont(AffineTransform.getRotateInstance(Math.toRadians(angle)))); } Rectangle2D sSize = g2.getFontMetrics().getStringBounds(text, g2); Point2D pos = getPoint(bounds, align); double x = pos.getX(); double y = pos.getY() + sSize.getHeight(); switch (align) { case TopCenter: case BottomCenter: case Center: x -= (sSize.getWidth() / 2); break; case TopRight: case MiddleRight: case BottomRight: x -= (sSize.getWidth()); break; case BottomLeft: case MiddleLeft: case TopLeft: break; } if (multiline) { // Create a new LineBreakMeasurer from the paragraph. // It will be cached and re-used. //if (lineMeasurer == null) { AttributedCharacterIterator paragraph = new AttributedString(text).getIterator(); paragraphStart = paragraph.getBeginIndex(); paragraphEnd = paragraph.getEndIndex(); FontRenderContext frc = g2.getFontRenderContext(); lineMeasurer = new LineBreakMeasurer(paragraph, frc); //} // Set break width to width of Component. float breakWidth = (float) bounds.getWidth(); float drawPosY = (float) y; // 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: this won't occur for the English text in this sample. // Note: drawPosX is always where the LEFT of the text is placed. float drawPosX = layout.isLeftToRight() ? (float) x : (float) x + breakWidth - layout.getAdvance(); // Move y-coordinate by the ascent of the layout. drawPosY += layout.getAscent(); // Draw the TextLayout at (drawPosX, drawPosY). layout.draw(g2, drawPosX, drawPosY); // Move y-coordinate in preparation for next layout. drawPosY += layout.getDescent() + layout.getLeading(); } } else { g2.drawString(text, (float) x, (float) y); } g2.setFont(font); }
From source file:com.pronoiahealth.olhie.server.services.BookCoverImageService.java
/** * Create an image that contains text//from ww w. ja v a 2s. 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:org.pentaho.reporting.engine.classic.core.layout.process.text.ComplexTextMinorAxisLayoutStep.java
private void addCompleteLine(final ParagraphRenderBox box, final ParagraphPoolBox lineBoxContainer, final StyleSheet layoutContext) { RichTextSpec richText = RichTextSpecProducer.compute(lineBoxContainer, metaData, resourceManager); final FontRenderContext fontRenderContext = createFontRenderContext(layoutContext); final TextLayout textLayout = new TextLayout(richText.createAttributedCharacterIterator(), fontRenderContext);// w w w . j ava 2 s.c o m double height = textLayout.getAscent() + textLayout.getDescent() + textLayout.getLeading(); final RenderableComplexText text = richText.create(lineBoxContainer); text.setTextLayout(textLayout); ParagraphFontMetricsImpl metrics = new ParagraphFontMetricsImpl(); metrics.update(textLayout); final RenderBox line = generateLine(box, lineBoxContainer, text, height, metrics); // and finally add the line to the paragraph getNodeContext().updateX2(line.getCachedX2()); box.addGeneratedChild(line); }
From source file:ru.runa.wfe.graph.image.figure.AbstractFigure.java
private int drawText(Graphics2D graphics, String text, int hOffset) { Rectangle r = getTextBoundsRectangle(); Rectangle2D textBounds = graphics.getFontMetrics().getStringBounds(text, graphics); if (textBounds.getWidth() > r.getWidth() - 4) { int y = coords[1] + hOffset; AttributedString attributedString = new AttributedString(text); attributedString.addAttribute(TextAttribute.FONT, graphics.getFont()); AttributedCharacterIterator characterIterator = attributedString.getIterator(); LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, graphics.getFontRenderContext()); while (measurer.getPosition() < characterIterator.getEndIndex()) { TextLayout textLayout = measurer.nextLayout((float) r.getWidth() - 4); y += textLayout.getAscent(); float x = (float) (r.getCenterX() + 2 - textLayout.getBounds().getCenterX()); textLayout.draw(graphics, x, y); y += textLayout.getDescent() + textLayout.getLeading(); }//w w w. j a v a 2s .com return y - coords[1]; } else { graphics.drawString(text, (float) (r.getCenterX() + 2 - textBounds.getCenterX()), (float) (coords[1] + textBounds.getHeight() + hOffset)); return (int) (textBounds.getHeight() + hOffset + 3); } }