Example usage for java.awt Graphics2D drawString

List of usage examples for java.awt Graphics2D drawString

Introduction

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

Prototype

public abstract void drawString(AttributedCharacterIterator iterator, float x, float y);

Source Link

Document

Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class.

Usage

From source file:com.celements.photo.image.GenerateThumbnail.java

private void drawString(String copyright, int width, int height, int bottomSpace, int rightSpace, int vSpacing,
        int hSpacing, FontMetrics metrics, Graphics2D g2d) {
    AlphaComposite transprency;//  ww w . ja v a 2  s .c om
    g2d.setColor(new Color(255, 255, 255));
    transprency = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.66f);
    g2d.setComposite(transprency);
    //Attention: drawString's [x, y] coordinates are the baseline, not upper or lower corner.
    g2d.drawString(copyright, width - metrics.stringWidth(copyright) - hSpacing - rightSpace,
            height - metrics.getDescent() - vSpacing - bottomSpace);
}

From source file:savant.view.tracks.TrackRenderer.java

/**
 * Draw a legend which consists of the given bases arranged horizontally
 *//* www. ja v  a 2s  . c  o  m*/
protected void drawBaseLegend(Graphics2D g2, int x, int y, ColourKey... keys) {
    ColourScheme cs = (ColourScheme) instructions.get(DrawingInstruction.COLOUR_SCHEME);
    g2.setFont(LEGEND_FONT);

    for (ColourKey k : keys) {
        g2.setColor(cs.getColor(k));
        g2.fillRect(x, y - SWATCH_SIZE.height + 2, SWATCH_SIZE.width, SWATCH_SIZE.height);
        g2.setColor(Color.BLACK);
        g2.drawString(k.getName(), x + SWATCH_SIZE.width + 3, y);
        x += 27;
    }
}

From source file:org.csml.tommo.sugar.modules.MappingQuality.java

protected void drawColumnHeader(Graphics2D g2, final MappingQualityTableModel model, int imgSize,
        int topBottomSeparator, int height, StringBuffer d) {

    // draw Top-Bottom header
    if (model.getTopBottomSeparatorColumn() > 0) {
        String s = "Top-Bottom";
        int stringWidth = g2.getFontMetrics().stringWidth(s);
        g2.drawString(s, 1 + imgSize * (model.getTopBottomSeparatorColumn() + 1)
                + (topBottomSeparator - 1 - stringWidth) / 2, 1 + height + 10 - 3);
    }/*  w  w  w. j  av a  2s  .  co m*/

    int separator = 0;
    for (int c = 0; c < model.getColumnCount(); c++) {
        d.append(model.getColumnName(c));
        d.append("\t");

        if (c == model.getTopBottomSeparatorColumn()) {
            d.append("Top-Bottom");
            d.append("\t");
        }
        Integer[] tiles = model.getTilesForColumn(c);
        for (int i = 0; i < tiles.length; i++) {
            String s = tiles[i].toString();
            int stringWidth = g2.getFontMetrics().stringWidth(s);
            g2.drawString(s, 1 + imgSize * c + (imgSize - 1 - stringWidth) / 2 + separator,
                    1 + height + 10 * (i + 1) - 3);
        }
        if (c == model.getTopBottomSeparatorColumn()) {
            separator = topBottomSeparator;
        }
    }
    d.append("\n");
}

From source file:uk.ac.babraham.BamQC.Graphs.ScatterGraph.java

@Override
protected void paintComponent(Graphics g) {

    g.setColor(Color.WHITE);/*www .j  a va  2s  .  co  m*/
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(Color.BLACK);

    if (g instanceof Graphics2D) {
        ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }

    double yStart, xStart;
    if (minY % yInterval == 0) {
        yStart = minY;
    } else {
        yStart = yInterval * (((int) minY / yInterval) + 1);
    }

    if (minX % xInterval == 0) {
        xStart = minX;
    } else {
        xStart = xInterval * (((int) minX / xInterval) + 1);
    }

    int xOffset = 0;

    // Draw the yLabel on the left of the yAxis
    int yLabelRightShift = 12;
    if (yLabel == null || yLabel.isEmpty()) {
        yLabelRightShift = 0;
    } else {
        if (g instanceof Graphics2D) {
            Graphics2D g2 = (Graphics2D) g;
            AffineTransform orig = g2.getTransform();
            g2.rotate(-Math.PI / 2);
            g2.setColor(Color.BLACK);
            g2.drawString(yLabel, -getY(-yInterval) / 2 - (g.getFontMetrics().stringWidth(yLabel) / 2),
                    yLabelRightShift);
            g2.setTransform(orig);
        }
    }

    // Draw the y axis labels
    int lastYLabelEnd = Integer.MAX_VALUE;
    for (double i = yStart; i <= maxY; i += yInterval) {
        String label = "" + i;
        label = label.replaceAll(".0$", ""); // Don't leave trailing .0s where we don't need them.
        // Calculate the new xOffset depending on the widest ylabel.
        int width = g.getFontMetrics().stringWidth(label);
        if (width > xOffset) {
            xOffset = width;
        }
        // place the y axis labels so that they don't overlap when the plot is resized.
        int baseNumberHeight = g.getFontMetrics().getHeight();
        int baseNumberPosition = getY(i) + (baseNumberHeight / 2);
        if (baseNumberPosition + baseNumberHeight < lastYLabelEnd) {
            // Draw the y axis labels
            g.drawString(label, yLabelRightShift + 6, baseNumberPosition);
            lastYLabelEnd = baseNumberPosition + 2;
        }
    }

    // Give the x axis a bit of breathing space
    xOffset = xOffset + yLabelRightShift + 8;

    // Now draw horizontal lines across from the y axis
    g.setColor(new Color(180, 180, 180));
    for (double i = yStart; i <= maxY; i += yInterval) {
        g.drawLine(xOffset, getY(i), getWidth() - 10, getY(i));
    }
    g.setColor(Color.BLACK);

    // Draw the graph title
    int titleWidth = g.getFontMetrics().stringWidth(graphTitle);
    g.drawString(graphTitle, (xOffset + ((getWidth() - (xOffset + 10)) / 2)) - (titleWidth / 2), 30);

    // Draw the xLabel under the xAxis
    g.drawString(xLabel, (getWidth() / 2) - (g.getFontMetrics().stringWidth(xLabel) / 2), getHeight() - 5);

    // Now draw the data points
    double baseWidth = (getWidth() - (xOffset + 10)) / (maxX - minX);

    //      System.out.println("Base Width is "+baseWidth);
    // Let's find the longest label, and then work out how often we can draw labels
    int lastXLabelEnd = 0;

    // Draw the x axis labels
    for (double i = xStart; i <= maxX; i += xInterval) {
        g.setColor(Color.BLACK);
        String baseNumber = "" + i;
        baseNumber = baseNumber.replaceAll(".0$", ""); // Don't leave trailing .0s where we don't need them.
        // Calculate the new xOffset depending on the widest ylabel.
        int baseNumberWidth = g.getFontMetrics().stringWidth(baseNumber);
        int baseNumberPosition = (int) (xOffset + (baseWidth * i) - (baseNumberWidth / 2));

        if (baseNumberPosition > lastXLabelEnd) {
            g.drawString(baseNumber, baseNumberPosition, getHeight() - 25);
            lastXLabelEnd = baseNumberPosition + baseNumberWidth + 5;
        }
        // Now draw vertical lines across from the y axis
        g.setColor(new Color(180, 180, 180));
        g.drawLine((int) (xOffset + (baseWidth * i)), getHeight() - 40, (int) (xOffset + (baseWidth * i)), 40);
        g.setColor(Color.BLACK);
    }

    // Now draw the axes
    g.drawLine(xOffset, getHeight() - 40, getWidth() - 10, getHeight() - 40);
    g.drawLine(xOffset, getHeight() - 40, xOffset, 40);

    // Initialise the arrays containing the tooltips
    rectangles = new ArrayList<Rectangle>();
    tips = new ArrayList<String>();

    g.setColor(Color.BLUE);
    // Draw the data points
    double ovalSize = 5;
    // We distinguish two inputs since the x label does not start from 0.
    // used for computing the actual line points as if they were starting from 0.
    double[] inputVar = new double[data.length];
    double[] responseVar = new double[data.length];
    for (int d = 0; d < data.length; d++) {
        double x = getX(xCategories[d], xOffset) - ovalSize / 2;
        double y = getY(data[d]) - ovalSize / 2;
        g.fillOval((int) x, (int) y, (int) (ovalSize), (int) (ovalSize));
        g.drawString(toolTipLabels[d], (int) x + 2, (int) y + 16);
        inputVar[d] = Double.valueOf(xCategories[d]);
        responseVar[d] = data[d];

        // Tool tips
        Rectangle r = new Rectangle((int) x, (int) y, (int) (ovalSize), (int) (ovalSize));
        rectangles.add(r);
        tips.add(toolTipLabels[d]);
    }
    g.setColor(Color.BLACK);

    // Draw the intercept 

    // WARNING: Is drawing a least squares regression line asserting that "the distribution follows a power law" correct?
    // This is our case if we plot log-log..
    // It seems not in this paper (Appendix A) http://arxiv.org/pdf/0706.1062v2.pdf

    if (data.length > 1) {
        LinearRegression linReg = new LinearRegression(inputVar, responseVar);
        double intercept = linReg.intercept();
        double slope = linReg.slope();
        double rSquare = linReg.R2();

        // Let's now calculate the two points (x1, y1) and (xn, yn)
        // (x1, y1). We need to skip the areas where x1<minY and y1>maxY
        double x1 = minX;
        double y1 = slope * minX + intercept;
        if (y1 < minY) {
            x1 = (minY - intercept) / slope;
            y1 = minY;
        } else if (y1 > maxY) {
            x1 = (maxY - intercept) / slope;
            y1 = maxY;
        }
        // (xn, yn). maxX which essentially is inputVar[inputVar.length-1]
        double xn = maxX;
        double yn = slope * maxX + intercept;

        if (g instanceof Graphics2D) {
            ((Graphics2D) g).setStroke(new BasicStroke(1.5f));
        }
        g.setColor(Color.RED);
        g.drawLine(getX(x1, xOffset), getY(y1), getX(xn, xOffset), getY(yn));
        g.setColor(Color.BLACK);
        if (g instanceof Graphics2D) {
            ((Graphics2D) g).setStroke(new BasicStroke(1));
        }

        // Draw the legend for the intercept
        String legendString = "y = " + Precision.round(slope, 3) + "x";
        if (intercept < 0)
            legendString += " - " + Precision.round(-intercept, 3);
        else
            legendString += " + " + Precision.round(intercept, 3);
        int width = g.getFontMetrics().stringWidth(legendString);

        // First draw a box to put the legend in
        g.setColor(Color.WHITE);
        g.fillRect(xOffset + 10, 45, width + 8, 35);
        g.setColor(Color.LIGHT_GRAY);
        g.drawRect(xOffset + 10, 45, width + 8, 35);

        // Now draw the legend label
        g.setColor(Color.RED);
        g.drawString(legendString, xOffset + 13, 60);
        g.drawString("R^2 = " + Precision.round(rSquare, 3), xOffset + 13, 76);
        g.setColor(Color.BLACK);
    }

}

From source file:savant.amino.AminoCanvas.java

private void paintAminoAcid(Graphics2D g2, AminoAcid a, int pos, int bases, int labelPos, boolean labelled) {
    if (a != null) {
        g2.setColor(new Color(a.color.getRed(), a.color.getGreen(), a.color.getBlue(), plugin.getAlpha()));
        double x0 = track.transformXPos(pos);
        double x1 = track.transformXPos(pos + bases);
        g2.fill(new Rectangle2D.Double(x0, 0.0, x1 - x0, getHeight()));
        if (labelled) {
            g2.setColor(a == AminoAcid.STOP ? Color.WHITE : Color.BLACK);
            double charWidth = g2.getFontMetrics().charWidth(a.code);
            g2.drawString(Character.toString(a.code),
                    (float) (track.transformXPos(labelPos) + track.transformXPos(labelPos + 3) - charWidth)
                            * 0.5F,//from  www .  jav  a 2  s .  c  o  m
                    getHeight() * 0.5F);
        }
    }
}

From source file:edu.purdue.cc.bionet.ui.HeatMap.java

/**
 * This method retrieves a heatmap image from jfreechart and places it on the panel
 * along with black divider lines and labels to create a heat map graph.
 * //from   w  w w.ja v  a  2  s . c om
 * @param g The Graphics for the jpanel.
 */
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (moleculeList.size() > 0) {
        float tickStep;
        BufferedImage drawing = HeatMapUtilities.createHeatMapImage(this.getDataset(), this.spectrum);
        int leftEdge = this.getWidth() / 8;
        int topEdge = this.getHeight() / 32;
        int bottomEdge = this.getHeight() * 7 / 8;
        int rightEdge = this.getWidth() * 31 / 32;
        mapPosition = new Rectangle(leftEdge, topEdge, rightEdge - leftEdge, bottomEdge - topEdge);
        g.drawImage(drawing, leftEdge, topEdge, rightEdge - leftEdge, bottomEdge - topEdge,
                this.getBackground(), this);
        // y-axis
        int yAxisPos = leftEdge - 1;
        //      g.drawLine( yAxisPos, topEdge, yAxisPos, bottomEdge );
        tickStep = (bottomEdge - topEdge) / (float) moleculeList.size();
        for (int i = 0; i <= moleculeList.size(); i++) {
            int tickY = Math.round(topEdge + i * tickStep);
            g.drawLine(rightEdge, tickY, yAxisPos - tickSize, tickY);
            if (i < moleculeList.size()) {
                String name = this.moleculeList.get(this.moleculeList.size() - 1 - i).toString();
                g.drawString(name, yAxisPos - 4 - g.getFontMetrics().stringWidth(name),
                        (int) (tickY + tickStep));
            }
        }

        // x-axis
        int xAxisPos = bottomEdge;
        tickStep = (rightEdge - leftEdge) / (float) moleculeList.size();
        //      g.drawLine( leftEdge, xAxisPos, rightEdge, xAxisPos );
        for (int i = 0; i <= moleculeList.size(); i++) {
            int tickX = (int) (leftEdge + i * tickStep);
            g.drawLine(tickX, topEdge, tickX, xAxisPos + tickSize);
        }
        // transform clockwise 90 degrees for the vertical text
        AffineTransform at = new AffineTransform();
        at.quadrantRotate(3);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.transform(at);
        for (int i = 0; i < moleculeList.size(); i++) {
            int tickX = Math.round(leftEdge + i * tickStep);
            String name = this.moleculeList.get(i).toString();
            g2d.drawString(name, -(int) (xAxisPos + 4 + g.getFontMetrics().stringWidth(name)),
                    (int) (tickX + tickStep));
        }
    }
}

From source file:TextRendering.java

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    Dimension d = getSize();/*from  w  w w .j  a  v  a 2 s  . com*/
    AffineTransform ct = AffineTransform.getTranslateInstance(d.width / 2, d.height * 3 / 4);
    g2.transform(ct);

    String s = "www.java2s.com";
    Font f = new Font("Serif", Font.PLAIN, 128);
    g2.setFont(f);

    int count = 6;
    for (int i = 1; i <= count; i++) {
        AffineTransform oldTransform = g2.getTransform();

        float ratio = (float) i / (float) count;
        g2.transform(AffineTransform.getRotateInstance(Math.PI * (ratio - 1.0f)));
        float alpha = ((i == count) ? 1.0f : ratio / 3);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        g2.drawString(s, 0, 0);

        g2.setTransform(oldTransform);
    }
}

From source file:org.uva.itast.blended.omr.OMRUtils.java

public static void logFrame(PageImage pageImage, PagePoint topleft, PagePoint topright, PagePoint bottomleft,
        PagePoint bottomright, Color color, String label) {
    if (topleft == null || topright == null || bottomleft == null || bottomright == null)
        return;/*from w w w . ja v a2  s  . c o m*/

    Graphics2D g = pageImage.getReportingGraphics();
    AffineTransform t = g.getTransform();
    g.setColor(color);
    g.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1,
            new float[] { (float) (3 / t.getScaleX()), (float) (6 / t.getScaleY()) }, 0));

    // Point framePxUL=pageImage.toPixels(topleft.getX(), topleft.getY());
    // Point framePxUR=pageImage.toPixels(topright.getX(), topright.getY());
    // Point framePxBL=pageImage.toPixels(bottomleft.getX(),
    // bottomleft.getY());
    // Point framePxBR=pageImage.toPixels(bottomright.getX(),
    // bottomright.getY());

    g.drawLine(topleft.getXpx(), topleft.getYpx(), topright.getXpx(), topright.getYpx());
    g.drawLine(topleft.getXpx(), topleft.getYpx(), bottomleft.getXpx(), bottomleft.getYpx());
    g.drawLine(topright.getXpx(), topright.getYpx(), bottomright.getXpx(), bottomright.getYpx());
    g.drawLine(bottomleft.getXpx(), bottomleft.getYpx(), bottomright.getXpx(), bottomright.getYpx());
    if (label != null) {
        g.drawString(label, topleft.getXpx(), topleft.getYpx());
    }
}

From source file:AntiAlias.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;
    BufferedImage image = // Create an off-screen image
            new BufferedImage(65, 35, BufferedImage.TYPE_INT_RGB);
    Graphics2D ig = image.createGraphics(); // Get its Graphics for drawing

    // Set the background to a gradient fill. The varying color of
    // the background helps to demonstrate the anti-aliasing effect
    ig.setPaint(new GradientPaint(0, 0, Color.black, 65, 35, Color.white));
    ig.fillRect(0, 0, 65, 35);//from  w  ww .ja  v  a2  s . c  o m

    // Set drawing attributes for the foreground.
    // Most importantly, turn on anti-aliasing.
    ig.setStroke(new BasicStroke(2.0f)); // 2-pixel lines
    ig.setFont(new Font("Serif", Font.BOLD, 18)); // 18-point font
    ig.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // Anti-alias!
            RenderingHints.VALUE_ANTIALIAS_ON);

    // Now draw pure blue text and a pure red oval
    ig.setColor(Color.blue);
    ig.drawString("Java", 9, 22);
    ig.setColor(Color.red);
    ig.drawOval(1, 1, 62, 32);

    // Finally, scale the image by a factor of 10 and display it
    // in the window. This will allow us to see the anti-aliased pixels
    g.drawImage(image, AffineTransform.getScaleInstance(10, 10), this);

    // Draw the image one more time at its original size, for comparison
    g.drawImage(image, 0, 0, this);
}

From source file:org.springframework.cloud.stream.app.pose.estimation.processor.PoseEstimateOutputMessageBuilder.java

private void drawPartOval(Part part, int radius, Graphics2D g) {
    int partX = part.getNormalizedX();
    int partY = part.getNormalizedY();

    g.setColor(GraphicsUtils.LIMBS_COLORS[part.getPartType().getId()]);
    g.fillOval(partX - radius, partY - radius, 2 * radius, 2 * radius);

    if (this.poseProperties.isDrawPartLabels()) {
        String label = part.getPartType().getId() + ":" + part.getPartType().name();
        FontMetrics fm = g.getFontMetrics();
        int labelX = partX + 5;
        int labelY = partY - 5;
        AffineTransform t = g.getTransform();
        g.setTransform(AffineTransform.getRotateInstance(Math.toRadians(-35), labelX, labelY));

        g.drawString(label, labelX, labelY);
        g.setTransform(t);//from w  ww.  j  a  v  a2s  . c  o  m
    }

}