@Override public void paintEntity(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setFont(Main.getHandlerForElement(this).getFontHandler().getFont()); colorize(g2); // enable colors g2.setColor(fgColor); g2.fillOval(0, 0, getRectangle().width, getRectangle().height); // Measure the font and the message Rectangle2D bounds = Main.getHandlerForElement(this) .getFontHandler() .getFont() .getStringBounds("H", g2.getFontRenderContext()); LineMetrics metrics = Main.getHandlerForElement(this) .getFontHandler() .getFont() .getLineMetrics("H", g2.getFontRenderContext()); float width = (float) bounds.getWidth(); // The width of our text float lineheight = metrics.getHeight(); // Total line height float ascent = metrics.getAscent(); // Top of text to baseline // Now display the message centered horizontally and vertically in this float x0 = (getRectangle().width - width) / 2; float y0 = (getRectangle().height - lineheight) / 2 + ascent; g2.setColor(Color.WHITE); g2.drawString("H", x0, y0); g2.setColor(fgColor); }
public void tree(Graphics2D g2d, double size, int phase) { g2d.setColor(colors[phase % 3]); new TextLayout(theT.toString(), theFont, g2d.getFontRenderContext()).draw(g2d, 0.0f, 0.0f); if (size > 10.0) { AffineTransform at = new AffineTransform(); at.setToTranslation(Twidth, -0.1); at.scale(0.6, 0.6); g2d.transform(at); size *= 0.6; new TextLayout(theR.toString(), theFont, g2d.getFontRenderContext()).draw(g2d, 0.0f, 0.0f); at.setToTranslation(Rwidth + 0.75, 0); g2d.transform(at); Graphics2D g2dt = (Graphics2D) g2d.create(); at.setToRotation(-Math.PI / 2.0); g2dt.transform(at); tree(g2dt, size, phase + 1); g2dt.dispose(); at.setToTranslation(.75, 0); at.rotate(-Math.PI / 2.0); at.scale(-1.0, 1.0); at.translate(-Twidth, 0); g2d.transform(at); tree(g2d, size, phase); } g2d.setTransform(new AffineTransform()); }
private void drawEnemyMessage(Graphics2D g2d) { Font messageFont = new Font("Arial", Font.BOLD, 15); g2d.setFont(messageFont); if (enemyMoveChosen) { String text = ""; if (drawMoveApplication) { text = effectMessage; } else { text = enemy.getName() + " uses " + lastEnemyMove.getName() + " on " + MainCharacter.characterName + "!"; } ArrayList<String> lines = new ArrayList<>(); int width = (int) (messageFont.getStringBounds(text, g2d.getFontRenderContext()).getWidth()); if (width > cardButton.getWidth() * 2 + 40) { String[] split = text.split("\\s+"); int tempWidth = 0; int maxWidth = 0; String line = ""; for (int i = 0; i < split.length; i++) { tempWidth += (int) (messageFont .getStringBounds(split[i] + "_", g2d.getFontRenderContext()) .getWidth()); if (tempWidth > cardButton.getWidth() * 2 + 40) { tempWidth = (int) (messageFont .getStringBounds(split[i] + "_", g2d.getFontRenderContext()) .getWidth()); lines.add(line); line = split[i] + " "; } else { line = line + split[i] + " "; } if (tempWidth > maxWidth) { maxWidth = tempWidth; } } lines.add(line); } else { lines.add(text); } for (int i = 0; i < lines.size(); i++) { g2d.drawString(lines.get(i), cardButton.getX(), cardButton.getY() + 15 + 30 * i); } } else { g2d.drawString("The Enemy is deciding", cardButton.getX(), cardButton.getY() + 15); g2d.drawString("their move...", cardButton.getX(), cardButton.getY() + 15 + 30); } }
// TODO misleading name - is centered around point and scaled font but not scale center point // (probably :) public void drawAntialiasedTextCenteredNoScale( Graphics2D g2, String text, int fontSize, Position pos, ImmutablePoint center, Color fgColor, Color bgColor) { Color original = g2.getColor(); FontRenderContext frc = g2.getFontRenderContext(); TextLayout tl = new TextLayout(text, getFont(fontSize), frc); Rectangle2D bounds = tl.getBounds(); center = center.translate((int) (bounds.getWidth() / -2), (int) (bounds.getHeight() / -2)); if (bgColor != null) { g2.setColor(bgColor); g2.fillRect( getOffsetX(pos) + center.getX() - 6, getOffsetY(pos) + center.getY() - 5, 12 + (int) bounds.getWidth(), 10 + (int) bounds.getHeight()); } g2.setColor(fgColor); tl.draw( g2, getOffsetX(pos) + center.getX(), getOffsetY(pos) + center.getY() + (int) bounds.getHeight()); g2.setColor(original); }
public DriverTextEps(Graphics2D g2dummy, ClipContainer clipContainer, EpsStrategy strategy) { this.stringBounder = StringBounderUtils.asStringBounder(g2dummy); this.clipContainer = clipContainer; this.fontRenderContext = g2dummy.getFontRenderContext(); this.g2dummy = g2dummy; this.strategy = strategy; }
public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; String message = "Hello, World!"; Font f = new Font("Serif", Font.BOLD, 36); g2.setFont(f); FontRenderContext context = g2.getFontRenderContext(); Rectangle2D bounds = f.getStringBounds(message, context); double x = (getWidth() - bounds.getWidth()) / 2; double y = (getHeight() - bounds.getHeight()) / 2; double ascent = -bounds.getY(); double baseY = y + ascent; g2.drawString(message, (int) x, (int) baseY); g2.setPaint(Color.LIGHT_GRAY); g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY)); Rectangle2D rect = new Rectangle2D.Double(x, y, bounds.getWidth(), bounds.getHeight()); g2.draw(rect); }
@Override public Point paint(Graphics2D g2, Point p) { Position = p; Font tmp = g2.getFont(); g2.setFont(new Font("SansSerif", Font.PLAIN, 18)); Rectangle2D NBounds = g2.getFont().getStringBounds(Integer.toString(currentNumber), g2.getFontRenderContext()); g2.draw( Arrow2D.getArrow( new Point( (int) (getPosition().getX() + NBounds.getCenterX()), (int) (getPosition().getY() - NBounds.getHeight())), new Point( (int) (getPosition().getX() + NBounds.getCenterX()), (int) getPosition().getY()), 8, 30)); g2.drawString( Integer.toString(currentNumber), (float) Position.getX(), (float) (Position.getY() - NBounds.getHeight())); g2.setFont(tmp); ShapeSize = new Rectangle2D.Double(0, 0, NBounds.getWidth(), NBounds.getHeight() + NBounds.getHeight()); return new Point((int) (p.getX() + ShapeSize.getWidth()), (int) p.getY()); }
public void drawPage(Graphics2D g2) { FontRenderContext context = g2.getFontRenderContext(); Font f = new Font("Serif", Font.PLAIN, 72); GeneralPath clipShape = new GeneralPath(); TextLayout layout = new TextLayout("2426打印指南", f, context); AffineTransform transform = AffineTransform.getTranslateInstance(0, 72); Shape outline = layout.getOutline(transform); clipShape.append(outline, false); layout = new TextLayout("thank you", f, context); transform = AffineTransform.getTranslateInstance(0, 144); outline = layout.getOutline(transform); clipShape.append(outline, false); g2.draw(clipShape); g2.clip(clipShape); final int NLINES = 50; Point2D p = new Point2D.Double(0, 0); for (int i = 0; i < NLINES; i++) { double x = (2 * getWidth() * i) / NLINES; double y = (2 * getHeight() * (NLINES - 1 - i)) / NLINES; Point2D q = new Point2D.Double(x, y); g2.draw(new Line2D.Double(p, q)); } }
// print font info private void test2(Graphics g) { Graphics2D g2d = (Graphics2D) g; int line = 1; for (int i = 10; i <= 24; i += 2) { Font font = new Font("MS ゴシック", Font.PLAIN, i); FontMetrics fm = super.getFontMetrics(font); System.out.println("*****1"); System.out.println(fm); System.out.println("Leading(標準レディング (行間の間隔)):" + fm.getLeading()); g2d.setFont(font); g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); FontRenderContext frc = g2d.getFontRenderContext(); TextLayout layout = new TextLayout("アンチエイリアスフォントテスト", font, frc); layout.draw(g2d, 0, line * 50); Rectangle2D bounds = layout.getBounds(); bounds.setRect( bounds.getX() + 0, bounds.getY() + (line * 50), bounds.getWidth(), bounds.getHeight()); g2d.draw(bounds); System.out.println("*****2" + font); System.out.println("有効幅 :" + layout.getAdvance()); System.out.println("有効幅(v):" + layout.getVisibleAdvance()); System.out.println("アセント :" + layout.getAscent()); System.out.println("ディセント :" + layout.getDescent()); System.out.println("ベースライン:" + layout.getBaseline()); System.out.println("境界 :" + layout.getBounds()); line++; } }
// how to use TextLayout#draw private void test1(Graphics g) { Graphics2D g2d = (Graphics2D) g; Font font = new Font("SansSerif", Font.PLAIN, 14); g2d.setFont(font); g.setColor(Color.WHITE); g.fillRect(0, 0, getWidth(), getHeight()); g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setColor(Color.BLACK); g.drawString("drawStringこんにちはabc文字列アンチエイリアスあり", 50, 50); // g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, // RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setColor(Color.BLACK); g.drawString("drawStringこんにちはabc文字列アンチエイリアスなし", 50, 100); // g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, // RenderingHints.VALUE_TEXT_ANTIALIAS_ON); System.out.println(System.getProperty("awt.useSystemAAFontSettings")); // Java6 g.setColor(Color.BLACK); g.drawString("drawStringこんにちはabc文字列アンチエイリアスあり", 50, 150); // RenderingHints.VALUE_TEXT_ANTIALIAS_ONにすれば、TextLayoutの描画はにはアンチエイリアスがかかる。 FontRenderContext frc = g2d.getFontRenderContext(); TextLayout layout = new TextLayout("TextLayoutで文字列を描画", font, frc); // Rectangle2D bounds = layout.getBounds(); // bounds.setRect(50, 200, 50 + 400, 200 + 50); // g2d.draw(bounds); layout.draw(g2d, 50, 200); }
private static final void drawShadowedStringCentered( final Graphics2D g2d, final String str, final double x, final double y, final Font font, final Paint paint, final double shadowOffset, final Paint shadowPaint) { g2d.setFont(font); final FontRenderContext frc = g2d.getFontRenderContext(); final Rectangle2D bounds = font.getStringBounds(str, frc); final LineMetrics metrics = font.getLineMetrics(str, frc); final double width = bounds.getWidth(); // The width of our text final float lineHeight = metrics.getHeight(); // Total line height final float ascent = metrics.getAscent(); // Top of text to baseline final double cx = (x + (0 - width) / 2); final double cy = (y + (0 - lineHeight) / 2 + ascent); if (shadowOffset > 0) { drawString(g2d, str, cx + shadowOffset, cy - shadowOffset, shadowPaint); drawString(g2d, str, cx + shadowOffset, cy + shadowOffset, shadowPaint); drawString(g2d, str, cx - shadowOffset, cy - shadowOffset, shadowPaint); drawString(g2d, str, cx - shadowOffset, cy + shadowOffset, shadowPaint); } drawString(g2d, str, cx, cy, paint); }
/** * Draw a string with given reference point and rotation angle. (0.5, 0.5) is center, (0, 0) is * lower left, (1, 0) is upper left, etc. The angle of rotation is in radians. The logical are * proportional to the base coordinates. */ public void drawTextBaseRatio( String label, double horizontalReference, double verticalReference, double rotation, double[] coord) { int[] sc = projection.screenProjectionBaseRatio(coord); int x = sc[0]; int y = sc[1]; AffineTransform transform = g2d.getTransform(); // Corner offset adjustment : Text Offset is used Here FontRenderContext frc = g2d.getFontRenderContext(); Font font = g2d.getFont(); double w = font.getStringBounds(label, frc).getWidth(); double h = font.getSize2D(); if (rotation != 0) { g2d.rotate(rotation, x, y); } x -= (int) (w * horizontalReference); y += (int) (h * verticalReference); g2d.drawString(label, x, y); g2d.setTransform(transform); }
public void paintComponent(Graphics g) { if (started) { width = this.getPreferredSize().getWidth(); height = this.getPreferredSize().getHeight(); double maxY = 0.0; Graphics2D g2 = (Graphics2D) g; g2.setRenderingHints(hints); // Disable the glasspane fade // g2.setColor(new Color(255, 255, 255, (int) (alphaLevel * shield))); // g2.drawRect(0, 0, getWidth(), getHeight()); for (int i = 0; i < ticker.length; i++) { int channel = 224 - 128 / (i + 1); g2.setColor(new Color(channel, channel, channel, alphaLevel)); g2.fill(ticker[i]); Rectangle2D bounds = ticker[i].getBounds2D(); if (bounds.getMaxY() > maxY) maxY = bounds.getMaxY(); } if (text != null && text.length() > 0) { FontRenderContext context = g2.getFontRenderContext(); TextLayout layout = new TextLayout(text, getFont(), context); Rectangle2D bounds = layout.getBounds(); g2.setColor(getForeground()); layout.draw( g2, (float) (width - bounds.getWidth()) / 2, (float) (maxY + layout.getLeading() + 2 * layout.getAscent())); } } }
@Override protected void paintIcon( java.awt.Component c, java.awt.Graphics2D g2, int width, int height, java.awt.Paint fillPaint, java.awt.Paint drawPaint) { java.awt.Font prevFont = g2.getFont(); g2.setFont(font); String text = "A"; java.awt.FontMetrics fm = g2.getFontMetrics(); int messageWidth = fm.stringWidth(text); int ascent = fm.getMaxAscent(); int descent = fm.getMaxDescent(); int x = (width / 2) - (messageWidth / 2); int y = ((height / 2) + (ascent / 2)) - (descent / 2); java.awt.font.GlyphVector glyphVector = font.createGlyphVector(g2.getFontRenderContext(), text); java.awt.Shape outline = glyphVector.getOutline(x, y); g2.setPaint(drawPaint); g2.draw(outline); g2.setPaint(fillPaint); g2.fill(outline); // g2.drawString( text, x, y ); g2.setFont(prevFont); }
/** * @param g2 * @throws IOException */ private void drawNode(Map<String, Node> nodes, Graphics2D g2, Font font) throws IOException { for (Node node : nodes.values()) { String name = node.getName(); if (nodeInfos.get(node.getType()) != null) { BufferedImage bi2 = ImageIO.read(getClass().getResourceAsStream( "icons/48/" + nodeInfos.get(node.getType()))); g2.drawImage(bi2, node.getX(), node.getY(), null); } else { int x = node.getX(); int y = node.getY(); int w = node.getWitdth(); int h = node.getHeight(); g2.setColor(DEFAULT_FILL_COLOR); g2.fillRoundRect(x, y, w, h, RECT_ROUND, RECT_ROUND); g2.setColor(DEFAULT_STROKE_COLOR); g2.setStroke(DEFAULT_STROKE); g2.drawRoundRect(x, y, w, h, RECT_ROUND, RECT_ROUND); FontRenderContext frc = g2.getFontRenderContext(); Rectangle2D r2 = font.getStringBounds(name, frc); int xLabel = (int) (node.getX() + ((node.getWitdth() - r2.getWidth()) / 2)); int yLabel = (int) ((node.getY() + ((node.getHeight() - r2.getHeight()) / 2)) - r2.getY()); g2.setStroke(DEFAULT_LINE_STROKE); g2.setColor(Color.black); g2.drawString(name, xLabel, yLabel); } } }
/** * @see org.jfree.chart.axis.Axis#refreshTicks(java.awt.Graphics2D, java.awt.geom.Rectangle2D, * java.awt.geom.Rectangle2D, int) */ public void refreshTicks( Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, int location) { // getTicks().clear(); Font tickLabelFont = getTickLabelFont(); g2.setFont(tickLabelFont); double size = getTickUnit().getSize(); int count = calculateVisibleTickCount(); double lowestTickValue = calculateLowestVisibleTickValue(); if (count <= ValueAxis.MAXIMUM_TICK_COUNT) { for (int i = 0; i < count; i++) { double currentTickValue = lowestTickValue + (i * size); double yy = translateValueToJava2D(currentTickValue, dataArea, RectangleEdge.BOTTOM); String tickLabel; NumberFormat formatter = getNumberFormatOverride(); if (formatter != null) { tickLabel = formatter.format(currentTickValue); } else { tickLabel = valueToString(currentTickValue); } FontRenderContext frc = g2.getFontRenderContext(); Rectangle2D tickLabelBounds = tickLabelFont.getStringBounds(longestStr, frc); LineMetrics lm = tickLabelFont.getLineMetrics(tickLabel, frc); float x = (float) (dataArea.getX() - tickLabelBounds.getWidth() - getTickLabelInsets().right); float y = (float) (yy + (lm.getAscent() / 2)); // Tick tick = new Tick(new Double(currentTickValue), tickLabel, x, y); // getTicks().add(tick); } } }
public int getBitmapFontRAMUsage() { BufferedImage image = new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = (Graphics2D) image.getGraphics(); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, bitmapAntialiasing); g2d.setFont(java.awt.Font.decode(lookupFont)); FontMetrics metrics = g2d.getFontMetrics(); FontRenderContext context = g2d.getFontRenderContext(); int baseline = (int) Math.ceil(metrics.getMaxAscent()); int[] offsets = new int[bitmapCharset.length()]; int[] widths = new int[offsets.length]; int currentOffset = 0; for (int iter = 0; iter < bitmapCharset.length(); iter++) { offsets[iter] = currentOffset; String currentChar = bitmapCharset.substring(iter, iter + 1); g2d.drawString(currentChar, currentOffset, baseline); Rectangle2D rect = g2d.getFont().getStringBounds(currentChar, context); widths[iter] = (int) Math.ceil(rect.getWidth()); // max advance works but it makes a HUGE image in terms of width which // occupies more ram if (g2d.getFont().isItalic()) { currentOffset += metrics.getMaxAdvance(); } else { currentOffset += widths[iter] + 1; } } g2d.dispose(); return currentOffset * getHeight() * 4; }
/** * Estimates the maximum tick label height. * * @param g2 the graphics device. * @return The maximum height. * @since 1.0.7 */ protected double estimateMaximumTickLabelHeight(Graphics2D g2) { RectangleInsets tickLabelInsets = getTickLabelInsets(); double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom(); Font tickLabelFont = getTickLabelFont(); FontRenderContext frc = g2.getFontRenderContext(); result += tickLabelFont.getLineMetrics("123", frc).getHeight(); return result; }
public void render(int w, int h, Graphics2D g2) { Rectangle r = new Rectangle(10, 10, w - 20, h / 2 - 20); g2.setPaint(gradient); g2.fill(r); g2.setPaint(Color.green); g2.setStroke(new BasicStroke(20)); g2.draw(r); g2.setPaint(blacklines); g2.setStroke(new BasicStroke(15)); g2.draw(r); Font f = new Font("Times New Roman", Font.BOLD, w / 5); TextLayout tl = new TextLayout("Texture", f, g2.getFontRenderContext()); int sw = (int) tl.getBounds().getWidth(); int sh = (int) tl.getBounds().getHeight(); Shape sha = tl.getOutline(AffineTransform.getTranslateInstance(w / 2 - sw / 2, h * .25 + sh / 2)); g2.setColor(Color.black); g2.setStroke(new BasicStroke(3)); g2.draw(sha); g2.setPaint(greendots); g2.fill(sha); r.setLocation(10, h / 2 + 10); g2.setPaint(triangles); g2.fill(r); g2.setPaint(blacklines); g2.setStroke(new BasicStroke(20)); g2.draw(r); g2.setPaint(Color.green); g2.setStroke(new BasicStroke(4)); g2.draw(r); f = new Font("serif", Font.BOLD, w / 4); tl = new TextLayout("Paint", f, g2.getFontRenderContext()); sw = (int) tl.getBounds().getWidth(); sh = (int) tl.getBounds().getHeight(); sha = tl.getOutline(AffineTransform.getTranslateInstance(w / 2 - sw / 2, h * .75 + sh / 2)); g2.setColor(Color.black); g2.setStroke(new BasicStroke(5)); g2.draw(sha); g2.setPaint(bluedots); g2.fill(sha); }
private void doDrawString(Graphics2D g, int fragmentIndex, int x, int y) { String text = myFragments.get(fragmentIndex); if (StringUtil.isEmpty(text)) return; TextLayout layout = getTextLayout(fragmentIndex, g.getFont(), g.getFontRenderContext()); if (layout != null) { layout.draw(g, x, y); } else { g.drawString(text, x, y); } }
/** * Gets the page count of this section. * * @param g2 the graphics context * @param pf the page format * @return the number of pages needed */ public int getPageCount(Graphics2D g2, PageFormat pf) { if (message.equals("")) return 0; FontRenderContext context = g2.getFontRenderContext(); Font f = new Font("Serif", Font.PLAIN, 72); Rectangle2D bounds = f.getStringBounds(message, context); scale = pf.getImageableHeight() / bounds.getHeight(); double width = scale * bounds.getWidth(); int pages = (int) Math.ceil(width / pf.getImageableWidth()); return pages; }
@Override public Point paint(Graphics2D g2, Point p) { Position = p; g2.drawString(Name, (float) Position.getX(), (float) Position.getY()); ShapeSize = g2.getFont().getStringBounds(Name, g2.getFontRenderContext()); return new Point((int) (p.getX() + ShapeSize.getWidth()), (int) p.getY()); }
public static CGSize sizeWithFont(String text, UIFont font) { Graphics2D graphicsContext = CGContext.UICurrentContext().xmlvmGetGraphics2D(); Font savedFont = graphicsContext.getFont(); Font awtFont = font.xmlvmGetFont(); graphicsContext.setFont(awtFont); Rectangle2D size = awtFont.getStringBounds(text, graphicsContext.getFontRenderContext()); graphicsContext.setFont(savedFont); return new CGSize( (float) size.getWidth(), text != null && text.length() > 0 ? (float) size.getHeight() : 0.0f); }
/** * @param s * @return */ private String[] splitOnBreaks(String s, double maxSize, Font ft) { List<String> al = new ArrayList<String>(); // check hard break first int i = 0, j; do { j = s.indexOf('\n', i); if (j == -1) { j = s.length(); } String ss = s.substring(i, j); if (ss != null && ss.length() > 0) { al.add(ss); } i = j + 1; } while (j != -1 && j < s.length()); // check wrapping if (maxSize > 0) { List<String> nal = new ArrayList<String>(); for (Iterator<String> itr = al.iterator(); itr.hasNext(); ) { String ns = itr.next(); AttributedString as = new AttributedString(ns, ft.getAttributes()); LineBreakMeasurer lbm = new LineBreakMeasurer(as.getIterator(), g2d.getFontRenderContext()); while (lbm.getPosition() < ns.length()) { int next = lbm.nextOffset((float) maxSize); String ss = ns.substring(lbm.getPosition(), next); lbm.setPosition(next); nal.add(ss); } } al = nal; } final int n = al.size(); if (n == 1 || n == 0) { return null; } final String[] sa = new String[n]; for (i = 0; i < al.size(); i++) { sa[i] = al.get(i); } return sa; }
/** * Allows reuse of the multi-line text element for computing bounds of changed font/text content * * @param fd */ public final void reuse(Label la, double forceWrappingSize) { final Font f = (Font) xs.createFont(la.getCaption().getFont()); fm = g2d.getFontMetrics(f); final FontRenderContext frc = g2d.getFontRenderContext(); cachedwidth = Double.NaN; String s = la.getCaption().getValue(); if (s == null) { s = IConstants.NULL_STRING; } else { // trim leading and trailing spaces. s = s.trim(); } if (s.length() == 0) // TextLayout DOESN'T LIKE EMPTY STRINGS { s = IConstants.ONE_SPACE; } String[] sa = splitOnBreaks(s, forceWrappingSize, f); if (sa == null) { iLineCount = 1; oText = s; tla = new TextLayout[1]; fsa = new String[1]; tla[0] = new TextLayout(s, f.getAttributes(), frc); fsa[0] = s; } else { iLineCount = sa.length; oText = sa; tla = new TextLayout[iLineCount]; fsa = new String[iLineCount]; for (int i = 0; i < iLineCount; i++) { tla[i] = new TextLayout(sa[i], f.getAttributes(), frc); fsa[i] = sa[i]; } } ins = la.getInsets().scaledInstance(pointsToPixels()); if (forceWrappingSize > 0) { // update label with new broken content. StringBuffer sb = new StringBuffer(); for (int i = 0; i < fsa.length; i++) { sb.append(fsa[i]).append("\n"); // $NON-NLS-1$ } if (sb.length() > 0) { sb.deleteCharAt(sb.length() - 1); } la.getCaption().setValue(sb.toString()); } }
public void render(int w, int h, Graphics2D g2) { FontRenderContext frc = g2.getFontRenderContext(); Font font = g2.getFont(); g2.setColor(Color.black); for (int i = 0; i < 3; i++) { g2.setStroke(new BasicStroke(15, cap[i], BasicStroke.JOIN_MITER)); g2.draw(new Line2D.Float(w / 4, (i + 1) * h / 4, w - w / 4, (i + 1) * h / 4)); TextLayout tl = new TextLayout(desc[i], font, frc); tl.draw(g2, (float) (w / 2 - tl.getBounds().getWidth() / 2), (i + 1) * h / 4 - 10); } }
/** @return the bitmapFont */ public Font getBitmapFont() { Font bitmapFont = Font.getBitmapFont(lookupFont); if (bitmapFont != null) { return bitmapFont; } BufferedImage image = new BufferedImage(5000, 50, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = (Graphics2D) image.getGraphics(); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, bitmapAntialiasing); g2d.setColor(Color.BLACK); g2d.fillRect(0, 0, image.getWidth(), image.getHeight()); g2d.setColor(new Color(0xff0000)); g2d.setFont(java.awt.Font.decode(lookupFont.split(";")[0])); FontMetrics metrics = g2d.getFontMetrics(); FontRenderContext context = g2d.getFontRenderContext(); int height = (int) Math.ceil(metrics.getMaxDescent() + metrics.getMaxAscent()); int baseline = (int) Math.ceil(metrics.getMaxAscent()); String charsetStr = bitmapCharset; int[] offsets = new int[charsetStr.length()]; int[] widths = new int[offsets.length]; int currentOffset = 0; for (int iter = 0; iter < charsetStr.length(); iter++) { offsets[iter] = currentOffset; String currentChar = charsetStr.substring(iter, iter + 1); g2d.drawString(currentChar, currentOffset, baseline); Rectangle2D rect = g2d.getFont().getStringBounds(currentChar, context); widths[iter] = (int) Math.ceil(rect.getWidth()); // max advance works but it makes a HUGE image in terms of width which // occupies more ram if (g2d.getFont().isItalic()) { currentOffset += metrics.getMaxAdvance(); } else { currentOffset += widths[iter] + 1; } } g2d.dispose(); BufferedImage shrunk = new BufferedImage(currentOffset, height, BufferedImage.TYPE_INT_RGB); g2d = (Graphics2D) shrunk.getGraphics(); g2d.drawImage(image, 0, 0, null); g2d.dispose(); int[] rgb = new int[shrunk.getWidth() * shrunk.getHeight()]; shrunk.getRGB(0, 0, shrunk.getWidth(), shrunk.getHeight(), rgb, 0, shrunk.getWidth()); com.sun.lwuit.Image bitmap = com.sun.lwuit.Image.createImage(rgb, shrunk.getWidth(), shrunk.getHeight()); return com.sun.lwuit.Font.createBitmapFont(lookupFont, bitmap, offsets, widths, charsetStr); }
/** * Creates a blank image with the given message painted on top (e.g., a loading or error message), * matching the size of the active reader's thumbnails. */ private BufferedImage makeImage(String message) { int w = reader.getThumbSizeX(), h = reader.getThumbSizeY(); if (w < 128) w = 128; if (h < 32) h = 32; BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); Rectangle2D.Float r = (Rectangle2D.Float) g.getFont().getStringBounds(message, g.getFontRenderContext()); g.drawString(message, (w - r.width) / 2, (h - r.height) / 2 + r.height); g.dispose(); return image; }
void drawCenteredString(Graphics2D g2d, String string, int x0, int y0, float angle) { FontRenderContext frc = g2d.getFontRenderContext(); Rectangle2D bounds = g2d.getFont().getStringBounds(string, frc); LineMetrics metrics = g2d.getFont().getLineMetrics(string, frc); if (angle == 0) { g2d.drawString(string, x0 - (float) bounds.getWidth() / 2, y0 + metrics.getHeight() / 2); } else { g2d.rotate(angle, x0, y0); g2d.drawString(string, x0 - (float) bounds.getWidth() / 2, y0 + metrics.getHeight() / 2); g2d.rotate(-angle, x0, y0); } }
/** * Get the text layouts for display if the string has changed since last call to this method * regenerate them. * * @param g2d Graphics2D display context * @return a list of text layouts for rendering */ public LinkedList<LineInfo> getLines(Graphics2D g2d) { if (font != g2d.getFont()) { setFont(g2d.getFont()); invalidText = true; } if (invalidText) { styledText = new AttributedString(plainText); setFont(font); applyAttributes(); invalidText = false; invalidLayout = true; } if (invalidLayout) { linesInfo.clear(); if (plainText.length() > 0) { textHeight = 0; maxLineLength = 0; maxLineHeight = 0; nbrLines = 0; AttributedCharacterIterator paragraph = styledText.getIterator(null, 0, plainText.length()); FontRenderContext frc = g2d.getFontRenderContext(); lineMeasurer = new LineBreakMeasurer(paragraph, frc); float yposinpara = 0; int charssofar = 0; while (lineMeasurer.getPosition() < plainText.length()) { TextLayout layout = lineMeasurer.nextLayout(wrapWidth); float advance = layout.getVisibleAdvance(); if (justify) { if (justify && advance > justifyRatio * wrapWidth) { // If advance > breakWidth then we have a line break float jw = (advance > wrapWidth) ? advance - wrapWidth : wrapWidth; layout = layout.getJustifiedLayout(jw); } } // Remember the longest and tallest value for a layout so far. float lh = getHeight(layout); if (lh > maxLineHeight) maxLineHeight = lh; textHeight += lh; if (advance <= wrapWidth && advance > maxLineLength) maxLineLength = advance; // Store layout and line info linesInfo.add( new LineInfo(nbrLines, layout, charssofar, layout.getCharacterCount(), yposinpara)); charssofar += layout.getCharacterCount(); yposinpara += lh; nbrLines++; } } invalidLayout = false; } return linesInfo; }