Example usage for java.awt Graphics2D getFontRenderContext

List of usage examples for java.awt Graphics2D getFontRenderContext

Introduction

In this page you can find the example usage for java.awt Graphics2D getFontRenderContext.

Prototype


public abstract FontRenderContext getFontRenderContext();

Source Link

Document

Get the rendering context of the Font within this Graphics2D context.

Usage

From source file:net.sourceforge.processdash.ui.web.reports.RadarPlot.java

/**
 * Draws the label for one radar axis./* w ww.  j a  va  2  s.c o m*/
 *
 * @param g2 The graphics device.
 * @param chartArea The area for the radar chart.
 * @param data The data for the plot.
 * @param axis The axis (zero-based index).
 * @param startAngle The starting angle.
 */
protected void drawLabel(Graphics2D g2, Rectangle2D chartArea, String label, int axis, double labelX,
        double labelY) {

    // handle label drawing...
    FontRenderContext frc = g2.getFontRenderContext();
    Rectangle2D labelBounds = this.axisLabelFont.getStringBounds(label, frc);
    LineMetrics lm = this.axisLabelFont.getLineMetrics(label, frc);
    double ascent = lm.getAscent();

    if (labelX == chartArea.getCenterX())
        labelX -= labelBounds.getWidth() / 2;
    else if (labelX < chartArea.getCenterX())
        labelX -= labelBounds.getWidth();
    if (labelY > chartArea.getCenterY())
        labelY += ascent;

    g2.setPaint(this.axisLabelPaint);
    g2.setFont(this.axisLabelFont);
    g2.drawString(label, (float) labelX, (float) labelY);
}

From source file:ParagraphLayout.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

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

    String s = "Java components and products Directory for Java components "
            + "and applications.Hundreds of Java components and applications "
            + "are organized by topic. You can find what you need easily. "
            + "You may also compare your product with others. If your component "
            + "is not listed, just send your url to java2s@java2s.com. " + "http://www.java2s.com";
    Font font = new Font("Serif", Font.PLAIN, 24);
    AttributedString as = new AttributedString(s);
    as.addAttribute(TextAttribute.FONT, font);
    AttributedCharacterIterator aci = as.getIterator();

    FontRenderContext frc = g2.getFontRenderContext();
    LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
    Insets insets = getInsets();//from  w  ww .  j a v a 2s .c  o m
    float wrappingWidth = getSize().width - insets.left - insets.right;
    float x = insets.left;
    float y = insets.top;

    while (lbm.getPosition() < aci.getEndIndex()) {
        TextLayout textLayout = lbm.nextLayout(wrappingWidth);
        y += textLayout.getAscent();
        textLayout.draw(g2, x, y);
        y += textLayout.getDescent() + textLayout.getLeading();
        x = insets.left;
    }
}

From source file:Chart.java

 public void paintComponent(Graphics g)
{
   Graphics2D g2 = (Graphics2D) g;

   // compute the minimum and maximum values
   if (values == null) return;
   double minValue = 0;
   double maxValue = 0;
   for (double v : values)
   {//ww  w .  ja va 2 s .c  om
      if (minValue > v) minValue = v;
      if (maxValue < v) maxValue = v;
   }
   if (maxValue == minValue) return;

   int panelWidth = getWidth();
   int panelHeight = getHeight();

   Font titleFont = new Font("SansSerif", Font.BOLD, 20);
   Font labelFont = new Font("SansSerif", Font.PLAIN, 10);

   // compute the extent of the title
   FontRenderContext context = g2.getFontRenderContext();
   Rectangle2D titleBounds = titleFont.getStringBounds(title, context);
   double titleWidth = titleBounds.getWidth();
   double top = titleBounds.getHeight();

   // draw the title
   double y = -titleBounds.getY(); // ascent
   double x = (panelWidth - titleWidth) / 2;
   g2.setFont(titleFont);
   g2.drawString(title, (float) x, (float) y);

   // compute the extent of the bar labels
   LineMetrics labelMetrics = labelFont.getLineMetrics("", context);
   double bottom = labelMetrics.getHeight();

   y = panelHeight - labelMetrics.getDescent();
   g2.setFont(labelFont);

   // get the scale factor and width for the bars
   double scale = (panelHeight - top - bottom) / (maxValue - minValue);
   int barWidth = panelWidth / values.length;

   // draw the bars
   for (int i = 0; i < values.length; i++)
   {
      // get the coordinates of the bar rectangle
      double x1 = i * barWidth + 1;
      double y1 = top;
      double height = values[i] * scale;
      if (values[i] >= 0) y1 += (maxValue - values[i]) * scale;
      else
      {
         y1 += maxValue * scale;
         height = -height;
      }

      // fill the bar and draw the bar outline
      Rectangle2D rect = new Rectangle2D.Double(x1, y1, barWidth - 2, height);
      g2.setPaint(Color.RED);
      g2.fill(rect);
      g2.setPaint(Color.BLACK);
      g2.draw(rect);

      // draw the centered label below the bar
      Rectangle2D labelBounds = labelFont.getStringBounds(names[i], context);

      double labelWidth = labelBounds.getWidth();
      x = x1 + (barWidth - labelWidth) / 2;
      g2.drawString(names[i], (float) x, (float) y);
   }
}

From source file:org.jax.haplotype.analysis.visualization.SimplePhylogenyTreeImageFactory.java

/**
 * Paint the given tree//  w  w w.  j  ava2s  .  co m
 * @param graphics
 *          the graphics to paint with
 * @param phylogenyTree
 *          the tree to paint
 */
private void paintPhylogenyTree(Graphics2D graphics, PhylogenyTreeNode phylogenyTree, int imageWidth,
        int imageHeight) {
    VisualTreeNode treeLayout = this.createTreeLayout(phylogenyTree);
    this.transformTreeLayout(treeLayout, imageWidth, imageHeight, graphics.getFontRenderContext());
    this.paintPhylogenyTree(graphics, treeLayout);
}

From source file:forge.view.arcane.util.OutlinedLabel.java

/** {@inheritDoc} */
@Override// ww w . j a v a 2s.  co  m
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:com.alibaba.simpleimage.render.FixDrawTextItem.java

@Override
public void drawText(Graphics2D graphics, int width, int height) {
    if (StringUtils.isBlank(text)) {
        return;/* w  ww  .  j av a2 s .c om*/
    }

    int x = 0, y = 0;
    int fontsize = 1;
    if (position == Position.CENTER) {
        // ?
        int textLength = (int) (width * textWidthPercent);
        // ??
        fontsize = textLength / text.length();
        // ?.....?
        if (fontsize < minFontSize) {
            return;
        }

        float fsize = (float) fontsize;
        Font font = defaultFont.deriveFont(fsize);
        graphics.setFont(font);
        FontRenderContext context = graphics.getFontRenderContext();
        int sw = (int) font.getStringBounds(text, context).getWidth();

        // ??
        x = (width - sw) / 2;
        y = height / 2 + fontsize / 2;
    } else if (position == Position.TOP_LEFT) {
        fontsize = ((int) (width * textWidthPercent)) / text.length();
        if (fontsize < minFontSize) {
            return;
        }

        float fsize = (float) fontsize;
        Font font = defaultFont.deriveFont(fsize);
        graphics.setFont(font);

        x = fontsize;
        y = fontsize * 2;
    } else if (position == Position.TOP_RIGHT) {
        fontsize = ((int) (width * textWidthPercent)) / text.length();
        if (fontsize < minFontSize) {
            return;
        }

        float fsize = (float) fontsize;
        Font font = defaultFont.deriveFont(fsize);
        graphics.setFont(font);
        FontRenderContext context = graphics.getFontRenderContext();
        int sw = (int) font.getStringBounds(text, context).getWidth();

        x = width - sw - fontsize;
        y = fontsize * 2;
    } else if (position == Position.BOTTOM_LEFT) {
        fontsize = ((int) (width * textWidthPercent)) / text.length();
        if (fontsize < minFontSize) {
            return;
        }

        float fsize = (float) fontsize;
        Font font = defaultFont.deriveFont(fsize);
        graphics.setFont(font);

        x = fontsize / 2;
        y = height - fontsize;
    } else if (position == Position.BOTTOM_RIGHT) {
        fontsize = ((int) (width * textWidthPercent)) / text.length();
        if (fontsize < minFontSize) {
            return;
        }

        float fsize = (float) fontsize;
        Font font = defaultFont.deriveFont(fsize);
        graphics.setFont(font);
        FontRenderContext context = graphics.getFontRenderContext();
        int sw = (int) font.getStringBounds(text, context).getWidth();

        x = width - sw - fontsize;
        y = height - fontsize;
    } else {
        throw new IllegalArgumentException("Unknown position : " + position);
    }

    if (x <= 0 || y <= 0) {
        return;
    }

    if (fontShadowColor != null) {
        graphics.setColor(fontShadowColor);
        graphics.drawString(text, x + getShadowTranslation(fontsize), y + getShadowTranslation(fontsize));
    }

    graphics.setColor(fontColor);
    graphics.drawString(text, x, y);
}

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

/**
 * Create an image that contains text// w w w  .ja  va  2  s. co m
 * 
 * @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:Paints.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;
    // Paint the entire background using a GradientPaint.
    // The background color varies diagonally from deep red to pale blue
    g.setPaint(new GradientPaint(0, 0, new Color(150, 0, 0), WIDTH, HEIGHT, new Color(200, 200, 255)));
    g.fillRect(0, 0, WIDTH, HEIGHT); // fill the background

    // Use a different GradientPaint to draw a box.
    // This one alternates between deep opaque green and transparent green.
    // Note: the 4th arg to Color() constructor specifies color opacity
    g.setPaint(new GradientPaint(0, 0, new Color(0, 150, 0), 20, 20, new Color(0, 150, 0, 0), true));
    g.setStroke(new BasicStroke(15)); // use wide lines
    g.drawRect(25, 25, WIDTH - 50, HEIGHT - 50); // draw the box

    // The glyphs of fonts can be used as Shape objects, which enables
    // us to use Java2D techniques with letters Just as we would with
    // any other shape. Here we get some letter shapes to draw.
    Font font = new Font("Serif", Font.BOLD, 10); // a basic font
    Font bigfont = // a scaled up version
            font.deriveFont(AffineTransform.getScaleInstance(30.0, 30.0));
    GlyphVector gv = bigfont.createGlyphVector(g.getFontRenderContext(), "JAV");
    Shape jshape = gv.getGlyphOutline(0); // Shape of letter J
    Shape ashape = gv.getGlyphOutline(1); // Shape of letter A
    Shape vshape = gv.getGlyphOutline(2); // Shape of letter V

    // We're going to outline the letters with a 5-pixel wide line
    g.setStroke(new BasicStroke(5.0f));

    // We're going to fake shadows for the letters using the
    // following Paint and AffineTransform objects
    Paint shadowPaint = new Color(0, 0, 0, 100); // Translucent black
    AffineTransform shadowTransform = AffineTransform.getShearInstance(-1.0, 0.0); // Shear to the right
    shadowTransform.scale(1.0, 0.5); // Scale height by 1/2

    // Move to the baseline of our first letter
    g.translate(65, 270);//ww w.  j  a v  a  2 s .  c o  m

    // Draw the shadow of the J shape
    g.setPaint(shadowPaint);
    g.translate(15, 20); // Compensate for the descender of the J
    // transform the J into the shape of its shadow, and fill it
    g.fill(shadowTransform.createTransformedShape(jshape));
    g.translate(-15, -20); // Undo the translation above

    // Now fill the J shape with a solid (and opaque) color
    g.setPaint(Color.blue); // Fill with solid, opaque blue
    g.fill(jshape); // Fill the shape
    g.setPaint(Color.black); // Switch to solid black
    g.draw(jshape); // And draw the outline of the J

    // Now draw the A shadow
    g.translate(75, 0); // Move to the right
    g.setPaint(shadowPaint); // Set shadow color
    g.fill(shadowTransform.createTransformedShape(ashape)); // draw shadow

    // Draw the A shape using a solid transparent color
    g.setPaint(new Color(0, 255, 0, 125)); // Transparent green as paint
    g.fill(ashape); // Fill the shape
    g.setPaint(Color.black); // Switch to solid back
    g.draw(ashape); // Draw the outline

    // Move to the right and draw the shadow of the letter V
    g.translate(175, 0);
    g.setPaint(shadowPaint);
    g.fill(shadowTransform.createTransformedShape(vshape));

    // We're going to fill the next letter using a TexturePaint, which
    // repeatedly tiles an image. The first step is to obtain the image.
    // We could load it from an image file, but here we create it
    // ourselves by drawing a into an off-screen image. Note that we use
    // a GradientPaint to fill the off-screen image, so the fill pattern
    // combines features of both Paint classes.
    BufferedImage tile = // Create an image
            new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB);
    Graphics2D tg = tile.createGraphics(); // Get its Graphics for drawing
    tg.setColor(Color.pink);
    tg.fillRect(0, 0, 50, 50); // Fill tile background with pink
    tg.setPaint(new GradientPaint(40, 0, Color.green, // diagonal gradient
            0, 40, Color.gray)); // green to gray
    tg.fillOval(5, 5, 40, 40); // Draw a circle with this gradient

    // Use this new tile to create a TexturePaint and fill the letter V
    g.setPaint(new TexturePaint(tile, new Rectangle(0, 0, 50, 50)));
    g.fill(vshape); // Fill letter shape
    g.setPaint(Color.black); // Switch to solid black
    g.draw(vshape); // Draw outline of letter

    // Move to the right and draw the shadow of the final A
    g.translate(160, 0);
    g.setPaint(shadowPaint);
    g.fill(shadowTransform.createTransformedShape(ashape));

    g.fill(ashape); // Fill letter A
    g.setPaint(Color.black); // Revert to solid black
    g.draw(ashape); // Draw the outline of the A
}

From source file:net.sf.mzmine.modules.visualization.metamsecorrelate.visual.pseudospectra.PseudoSpectraRenderer.java

@Override
protected void drawItemLabel(Graphics2D g2, XYDataset dataset, int series, int item, XYPlot plot,
        XYItemLabelGenerator generator, Rectangle2D bar, boolean negative) {
    //super.drawItemLabel(g2, dataset, series, item, plot, generator, bar, negative);  

    if (generator != null) {
        String label = generator.generateLabel(dataset, series, item);

        if (label != null) {
            Font labelFont = getItemLabelFont(series, item);
            Paint paint = getItemLabelPaint(series, item);
            g2.setFont(labelFont);/*from www  .  ja v a2s.  c om*/
            g2.setPaint(paint);

            // get the label position..
            ItemLabelPosition position;
            if (!negative) {
                position = getPositiveItemLabelPosition(series, item);
            } else {
                position = getNegativeItemLabelPosition(series, item);
            }

            // work out the label anchor point...
            Point2D anchorPoint = calculateLabelAnchorPoint(position.getItemLabelAnchor(), bar,
                    plot.getOrientation());

            // split by \n
            String symbol = "\n";
            String[] splitted = label.split(symbol);

            if (splitted.length > 1) {
                FontRenderContext frc = g2.getFontRenderContext();
                GlyphVector gv = g2.getFont().createGlyphVector(frc, "Fg,");
                int height = 4 + (int) gv.getPixelBounds(null, 0, 0).getHeight();
                // draw more than one row
                for (int i = 0; i < splitted.length; i++) {
                    int offset = -height * (splitted.length - i - 1);
                    TextUtilities.drawRotatedString(splitted[i], g2, (float) anchorPoint.getX(),
                            (float) anchorPoint.getY() + offset, position.getTextAnchor(), position.getAngle(),
                            position.getRotationAnchor());
                }
            } else {
                // one row 
                TextUtilities.drawRotatedString(label, g2, (float) anchorPoint.getX(),
                        (float) anchorPoint.getY(), position.getTextAnchor(), position.getAngle(),
                        position.getRotationAnchor());
            }
        }
    }

}

From source file:genlab.gui.jfreechart.EnhancedSpiderWebPlot.java

/**
 * Draws the label for one axis./* w w w .  j  av a 2  s.  co m*/
 *
 * @param g2  the graphics device.
 * @param plotArea  the plot area
 * @param value  the value of the label (ignored).
 * @param cat  the category (zero-based index).
 * @param startAngle  the starting angle.
 * @param extent  the extent of the arc.
 */
protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, double value, int cat, double startAngle,
        double extent) {
    FontRenderContext frc = g2.getFontRenderContext();

    String label = null;
    if (this.dataExtractOrder == TableOrder.BY_ROW) {
        // if series are in rows, then the categories are the column keys
        label = this.labelGenerator.generateColumnLabel(this.dataset, cat);
    } else {
        // if series are in columns, then the categories are the row keys
        label = this.labelGenerator.generateRowLabel(this.dataset, cat);
    }

    Rectangle2D labelBounds = getLabelFont().getStringBounds(label, frc);
    LineMetrics lm = getLabelFont().getLineMetrics(label, frc);
    double ascent = lm.getAscent();

    Point2D labelLocation = calculateLabelLocation(labelBounds, ascent, plotArea, startAngle);

    Composite saveComposite = g2.getComposite();

    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
    g2.setPaint(getLabelPaint());
    g2.setFont(getLabelFont());
    g2.drawString(label, (float) labelLocation.getX(), (float) labelLocation.getY());
    g2.setComposite(saveComposite);
}