Example usage for java.awt Graphics2D setFont

List of usage examples for java.awt Graphics2D setFont

Introduction

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

Prototype

public abstract void setFont(Font font);

Source Link

Document

Sets this graphics context's font to the specified font.

Usage

From source file:com.alibaba.simpleimage.render.FootnoteDrawTextItem.java

@Override
public void drawText(Graphics2D graphics, int width, int height) {
    if (StringUtils.isBlank(text) || StringUtils.isBlank(domainName)) {
        return;//w ww  .  j a  v  a 2  s.com
    }

    int x = 0, y = 0;
    int fontsize = ((int) (width * textWidthPercent)) / domainName.length();
    if (fontsize < minFontSize) {
        return;
    }

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

    x = width - sw - fontsize;
    y = height - fontsize;
    if (x <= 0 || y <= 0) {
        return;
    }

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

    //draw company name
    fsize = (float) fontsize;
    font = defaultFont.deriveFont(fsize);
    graphics.setFont(font);
    context = graphics.getFontRenderContext();
    sw = (int) font.getStringBounds(text, context).getWidth();
    x = width - sw - fontsize;
    y = height - (int) (fontsize * 2.5);
    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:figs.treeVisualization.gui.PhyloDateAxis.java

protected List<DateTick> refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea) {

    List<DateTick> result = new ArrayList<DateTick>();
    DateFormat formatter = getDateFormatOverride();

    Font tickLabelFont = getTickLabelFont();
    g2.setFont(tickLabelFont);

    if (isAutoTickUnitSelection()) {
        selectAutoTickUnit(g2, dataArea, RectangleEdge.RIGHT);
    }// w ww  .  java2  s  . c  o  m
    DateTickUnit unit = getTickUnit();

    // nextStandardDate is adding to the min which makes no sense, so just call previous
    Date tickDate = previousStandardDate(getMinimumDate(), unit);
    Date upperDate = getMaximumDate();
    while (!tickDate.after(upperDate)) {

        if (!isHiddenValue(tickDate.getTime())) {
            // work out the value, label and position
            String tickLabel;
            if (formatter != null) {
                tickLabel = formatter.format(tickDate);
            } else {
                tickLabel = this.getTickUnit().dateToString(tickDate);
            }
            TextAnchor anchor = null;
            TextAnchor rotationAnchor = null;
            double angle = 0.0;
            if (isVerticalTickLabels()) {
                anchor = TextAnchor.BOTTOM_CENTER;
                rotationAnchor = TextAnchor.BOTTOM_CENTER;
                // RectangeEdge.RIGHT
                angle = Math.PI / 2.0;
            } else {
                // RectangeEdge.RIGHT
                anchor = TextAnchor.CENTER_LEFT;
                rotationAnchor = TextAnchor.CENTER_LEFT;
            }

            DateTick tick = new DateTick(tickDate, tickLabel, anchor, rotationAnchor, angle);
            result.add(tick);
            tickDate = unit.addToDate(tickDate);
        } else {
            tickDate = unit.rollDate(tickDate);
        }
    }

    return result;
}

From source file:ImageOps.java

/** Draw the example */
public void paint(Graphics g1) {
    Graphics2D g = (Graphics2D) g1;
    // Create a BufferedImage big enough to hold the Image loaded
    // in the constructor. Then copy that image into the new
    // BufferedImage object so that we can process it.
    BufferedImage bimage = new BufferedImage(image.getWidth(this), image.getHeight(this),
            BufferedImage.TYPE_INT_RGB);
    Graphics2D ig = bimage.createGraphics();
    ig.drawImage(image, 0, 0, this); // copy the image

    // Set some default graphics attributes
    g.setFont(new Font("SansSerif", Font.BOLD, 12)); // 12pt bold text
    g.setColor(Color.green); // Draw in green
    g.translate(10, 10); // Set some margins

    // Loop through the filters
    for (int i = 0; i < filters.length; i++) {
        // If the filter is null, draw the original image, otherwise,
        // draw the image as processed by the filter
        if (filters[i] == null)
            g.drawImage(bimage, 0, 0, this);
        else//from   w w  w. j a v a 2  s. co  m
            g.drawImage(filters[i].filter(bimage, null), 0, 0, this);
        g.drawString(filterNames[i], 0, 205); // Label the image
        g.translate(137, 0); // Move over
        if (i % 4 == 3)
            g.translate(-137 * 4, 215); // Move down after 4
    }
}

From source file:org.optaplanner.examples.tsp.swingui.TspWorldPanel.java

public void resetPanel(TravelingSalesmanTour travelingSalesmanTour) {
    translator = new LatitudeLongitudeTranslator();
    for (Location location : travelingSalesmanTour.getLocationList()) {
        translator.addCoordinates(location.getLatitude(), location.getLongitude());
    }//  w w w . j  a v  a 2  s  .c om

    Dimension size = getSize();
    double width = size.getWidth();
    double height = size.getHeight();
    translator.prepareFor(width, height);

    Graphics2D g = createCanvas(width, height);
    String tourName = travelingSalesmanTour.getName();
    if (tourName.startsWith("europe")) {
        g.drawImage(europaBackground.getImage(), 0, 0, translator.getImageWidth(), translator.getImageHeight(),
                this);
    }
    g.setFont(g.getFont().deriveFont((float) LOCATION_NAME_TEXT_SIZE));
    g.setColor(TangoColorFactory.PLUM_2);
    List<Visit> visitList = travelingSalesmanTour.getVisitList();
    for (Visit visit : visitList) {
        Location location = visit.getLocation();
        int x = translator.translateLongitudeToX(location.getLongitude());
        int y = translator.translateLatitudeToY(location.getLatitude());
        g.fillRect(x - 1, y - 1, 3, 3);
        if (location.getName() != null && visitList.size() <= 500) {
            g.drawString(StringUtils.abbreviate(location.getName(), 20), x + 3, y - 3);
        }
    }
    g.setColor(TangoColorFactory.ALUMINIUM_4);
    Domicile domicile = travelingSalesmanTour.getDomicile();
    Location domicileLocation = domicile.getLocation();
    int domicileX = translator.translateLongitudeToX(domicileLocation.getLongitude());
    int domicileY = translator.translateLatitudeToY(domicileLocation.getLatitude());
    g.fillRect(domicileX - 2, domicileY - 2, 5, 5);
    if (domicileLocation.getName() != null && visitList.size() <= 500) {
        g.drawString(domicileLocation.getName(), domicileX + 3, domicileY - 3);
    }
    Set<Visit> needsBackToDomicileLineSet = new HashSet<Visit>(visitList);
    for (Visit trailingVisit : visitList) {
        if (trailingVisit.getPreviousStandstill() instanceof Visit) {
            needsBackToDomicileLineSet.remove(trailingVisit.getPreviousStandstill());
        }
    }
    g.setColor(TangoColorFactory.CHOCOLATE_1);
    for (Visit visit : visitList) {
        if (visit.getPreviousStandstill() != null) {
            Location previousLocation = visit.getPreviousStandstill().getLocation();
            Location location = visit.getLocation();
            translator.drawRoute(g, previousLocation.getLongitude(), previousLocation.getLatitude(),
                    location.getLongitude(), location.getLatitude(), location instanceof AirLocation, false);
            // Back to domicile line
            if (needsBackToDomicileLineSet.contains(visit)) {
                translator.drawRoute(g, location.getLongitude(), location.getLatitude(),
                        domicileLocation.getLongitude(), domicileLocation.getLatitude(),
                        location instanceof AirLocation, true);
            }
        }
    }
    // Drag
    if (dragSourceStandstill != null) {
        g.setColor(TangoColorFactory.CHOCOLATE_2);
        Location sourceLocation = dragSourceStandstill.getLocation();
        Location targetLocation = dragTargetStandstill.getLocation();
        translator.drawRoute(g, sourceLocation.getLongitude(), sourceLocation.getLatitude(),
                targetLocation.getLongitude(), targetLocation.getLatitude(),
                sourceLocation instanceof AirLocation, dragTargetStandstill instanceof Domicile);
    }
    // Legend
    g.setColor(TangoColorFactory.ALUMINIUM_4);
    g.fillRect(5, (int) height - 15 - TEXT_SIZE, 5, 5);
    g.drawString("Domicile", 15, (int) height - 10 - TEXT_SIZE);
    g.setColor(TangoColorFactory.PLUM_2);
    g.fillRect(6, (int) height - 9, 3, 3);
    g.drawString("Visit", 15, (int) height - 5);
    g.setColor(TangoColorFactory.ALUMINIUM_5);
    String locationsSizeString = travelingSalesmanTour.getLocationList().size() + " locations";
    g.drawString(locationsSizeString, ((int) width - g.getFontMetrics().stringWidth(locationsSizeString)) / 2,
            (int) height - 5);
    if (travelingSalesmanTour.getDistanceType() == DistanceType.AIR_DISTANCE) {
        String leftClickString = "Left click and drag between 2 locations to connect them.";
        g.drawString(leftClickString, (int) width - 5 - g.getFontMetrics().stringWidth(leftClickString),
                (int) height - 10 - TEXT_SIZE);
        String rightClickString = "Right click anywhere on the map to add a visit.";
        g.drawString(rightClickString, (int) width - 5 - g.getFontMetrics().stringWidth(rightClickString),
                (int) height - 5);
    }
    // Show soft score
    g.setColor(TangoColorFactory.ORANGE_3);
    SimpleLongScore score = travelingSalesmanTour.getScore();
    if (score != null) {
        String distanceString = travelingSalesmanTour.getDistanceString(NUMBER_FORMAT);
        g.setFont(g.getFont().deriveFont(Font.BOLD, (float) TEXT_SIZE * 2));
        g.drawString(distanceString, (int) width - g.getFontMetrics().stringWidth(distanceString) - 10,
                (int) height - 15 - 2 * TEXT_SIZE);
    }
    repaint();
}

From source file:ShowOff.java

protected float drawBoxedString(Graphics2D g2, String s, Color c1, Color c2, double x) {
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout subLayout = new TextLayout(s, mFont, frc);
    float advance = subLayout.getAdvance();

    GradientPaint gradient = new GradientPaint((float) x, 0, c1, (float) (x + advance), 0, c2);
    g2.setPaint(gradient);/*ww w.  ja va 2 s . c o m*/
    Rectangle2D bounds = mLayout.getBounds();
    Rectangle2D back = new Rectangle2D.Double(x, 0, advance, bounds.getHeight());
    g2.fill(back);

    g2.setPaint(Color.white);
    g2.setFont(mFont);
    g2.drawString(s, (float) x, (float) -bounds.getY());
    return advance;
}

From source file:edu.umn.cs.spatialHadoop.operations.GeometricPlot.java

/**
 * Draws an image that can be used as a scale for heat maps generated using
 * Plot or PlotPyramid.//from ww  w.  j a v  a2s  . c  om
 * @param output - Output path
 * @param valueRange - Range of values of interest
 * @param width - Width of the generated image
 * @param height - Height of the generated image
 * @throws IOException
 */
public static void drawScale(Path output, MinMax valueRange, int width, int height) throws IOException {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = image.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, width, height);

    // fix this part to work according to color1, color2 and gradient type
    for (int y = 0; y < height; y++) {
        Color color = NASARectangle.calculateColor(y);
        g.setColor(color);
        g.drawRect(width * 3 / 4, y, width / 4, 1);
    }

    int fontSize = 24;
    g.setFont(new Font("Arial", Font.BOLD, fontSize));
    int step = (valueRange.maxValue - valueRange.minValue) * fontSize * 10 / height;
    step = (int) Math.pow(10, Math.round(Math.log10(step)));
    int min_value = valueRange.minValue / step * step;
    int max_value = valueRange.maxValue / step * step;

    for (int value = min_value; value <= max_value; value += step) {
        int y = fontSize + (height - fontSize)
                - value * (height - fontSize) / (valueRange.maxValue - valueRange.minValue);
        g.setColor(Color.WHITE);
        g.drawString(String.valueOf(value), 5, y);
    }

    g.dispose();

    FileSystem fs = output.getFileSystem(new Configuration());
    FSDataOutputStream outStream = fs.create(output, true);
    ImageIO.write(image, "png", outStream);
    outStream.close();
}

From source file:org.esa.snap.graphbuilder.rcp.dialogs.support.GraphNode.java

/**
 * Draw a GraphNode as a rectangle with a name
 *
 * @param g   The Java2D Graphics// w  w  w  .  ja va2  s.  c  o  m
 * @param col The color to draw
 */
public void drawNode(final Graphics2D g, final Color col) {
    final int x = displayPosition.x;
    final int y = displayPosition.y;

    g.setFont(g.getFont().deriveFont(Font.BOLD, 11));
    final FontMetrics metrics = g.getFontMetrics();
    final String name = node.getId();
    final Rectangle2D rect = metrics.getStringBounds(name, g);
    final int stringWidth = (int) rect.getWidth();
    setSize(Math.max(stringWidth, 50) + 10, 25);

    int step = 4;
    int alpha = 96;
    for (int i = 0; i < step; ++i) {
        g.setColor(new Color(0, 0, 0, alpha - (32 * i)));
        g.drawLine(x + i + 1, y + nodeHeight + i, x + nodeWidth + i - 1, y + nodeHeight + i);
        g.drawLine(x + nodeWidth + i, y + i, x + nodeWidth + i, y + nodeHeight + i);
    }

    Shape clipShape = new Rectangle(x, y, nodeWidth, nodeHeight);

    g.setComposite(AlphaComposite.SrcAtop);
    g.setPaint(new GradientPaint(x, y, col, x + nodeWidth, y + nodeHeight, col.darker()));
    g.fill(clipShape);

    g.setColor(Color.blue);
    g.draw3DRect(x, y, nodeWidth - 1, nodeHeight - 1, true);

    g.setColor(Color.BLACK);
    g.drawString(name, x + (nodeWidth - stringWidth) / 2, y + 15);
}

From source file:org.gbif.portal.web.controller.dataset.IndexingHistoryController.java

/**
 * Create a time series graphic to display indexing processes.
 * //from   w  w  w.  j  a  v a  2  s  .  co  m
 * @param dataProvider
 * @param dataResource
 * @param activities
 * @param fileNamePrefix
 * @return
 */
public String timeSeriesTest(DataProviderDTO dataProvider, DataResourceDTO dataResource,
        List<LoggedActivityDTO> loggedActivities, String fileNamePrefix, int minProcessingTimeToRender) {

    List<LoggedActivityDTO> activities = new ArrayList<LoggedActivityDTO>();
    for (LoggedActivityDTO la : loggedActivities) {
        if (la.getDataResourceKey() != null && la.getDataResourceName() != null && la.getEventName() != null)
            activities.add(la);
    }

    //if no activities to render, return
    if (activities.isEmpty())
        return null;

    Map<String, Integer> drActualCount = new HashMap<String, Integer>();
    Map<String, Integer> drCount = new HashMap<String, Integer>();

    //record the actual counts
    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {
            if (drActualCount.get(laDTO.getDataResourceName()) == null) {
                drActualCount.put(laDTO.getDataResourceName(), new Integer(4));
                drCount.put(laDTO.getDataResourceName(), new Integer(0));
            } else {
                Integer theCount = drActualCount.get(laDTO.getDataResourceName());
                theCount = new Integer(theCount.intValue() + 4);
                drActualCount.remove(laDTO.getDataResourceName());
                drActualCount.put(laDTO.getDataResourceName(), theCount);
            }
        }
    }

    StringBuffer fileNameBuffer = new StringBuffer(fileNamePrefix);
    if (dataResource != null) {
        fileNameBuffer.append("-resource-");
        fileNameBuffer.append(dataResource.getKey());
    } else if (dataProvider != null) {
        fileNameBuffer.append("-provider-");
        fileNameBuffer.append(dataProvider.getKey());
    }
    fileNameBuffer.append(".png");

    String fileName = fileNameBuffer.toString();
    String filePath = System.getProperty("java.io.tmpdir") + File.separator + fileName;

    File fileToCheck = new File(filePath);
    if (fileToCheck.exists()) {
        return fileName;
    }

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    boolean generateChart = false;

    int count = 1;
    int dataResourceCount = 1;

    Collections.sort(activities, new Comparator<LoggedActivityDTO>() {
        public int compare(LoggedActivityDTO o1, LoggedActivityDTO o2) {
            if (o1 == null || o2 == null || o1.getDataResourceKey() != null || o2.getDataResourceKey() != null)
                return -1;
            return o1.getDataResourceKey().compareTo(o2.getDataResourceKey());
        }
    });

    String currentDataResourceKey = activities.get(0).getDataResourceKey();

    for (LoggedActivityDTO laDTO : activities) {
        if (laDTO.getStartDate() != null && laDTO.getEndDate() != null
                && laDTO.getDurationInMillisecs() > minProcessingTimeToRender) {

            if (currentDataResourceKey != null && !currentDataResourceKey.equals(laDTO.getDataResourceKey())) {
                dataResourceCount++;
                count = count + 1;
                currentDataResourceKey = laDTO.getDataResourceKey();
            }
            TimeSeries s1 = new TimeSeries(laDTO.getDataResourceName(), "Process time period",
                    laDTO.getEventName(), Hour.class);
            s1.add(new Hour(laDTO.getStartDate()), count);
            s1.add(new Hour(laDTO.getEndDate()), count);
            dataset.addSeries(s1);
            generateChart = true;
        }
    }

    if (!generateChart)
        return null;

    // create a pie chart...
    final JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false);

    XYPlot plot = chart.getXYPlot();
    plot.setWeight(10);
    plot.getRangeAxis().setAutoRange(false);
    plot.getRangeAxis().setRange(0, drCount.size() + 1);
    plot.getRangeAxis().setAxisLineVisible(false);
    plot.getRangeAxis().setAxisLinePaint(Color.WHITE);
    plot.setDomainCrosshairValue(1);
    plot.setRangeGridlinesVisible(false);
    plot.getRangeAxis().setVisible(false);
    plot.getRangeAxis().setLabel("datasets");

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setItemLabelsVisible(true);
    MyXYItemLabelGenerator labelGenerator = new MyXYItemLabelGenerator();
    labelGenerator.setDataResourceActualCount(drActualCount);
    labelGenerator.setDataResourceCount(drCount);
    renderer.setItemLabelGenerator(labelGenerator);

    List<TimeSeries> seriesList = dataset.getSeries();
    for (TimeSeries series : seriesList) {
        if (((String) series.getRangeDescription()).startsWith("extraction")) {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.RED);
        } else {
            renderer.setSeriesPaint(seriesList.indexOf(series), Color.BLUE);
        }
        renderer.setSeriesStroke(seriesList.indexOf(series), new BasicStroke(7f));
    }

    int imageHeight = 30 * dataResourceCount;
    if (imageHeight < 100) {
        imageHeight = 100;
    } else {
        imageHeight = imageHeight + 100;
    }

    final BufferedImage image = new BufferedImage(900, imageHeight, BufferedImage.TYPE_INT_RGB);
    KeypointPNGEncoderAdapter adapter = new KeypointPNGEncoderAdapter();
    adapter.setQuality(1);
    try {
        adapter.encode(image);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    final Graphics2D g2 = image.createGraphics();
    g2.setFont(new Font("Arial", Font.PLAIN, 11));
    final Rectangle2D chartArea = new Rectangle2D.Double(0, 0, 900, imageHeight);

    // draw
    chart.draw(g2, chartArea, null, null);

    //styling
    chart.setPadding(new RectangleInsets(0, 0, 0, 0));
    chart.setBorderVisible(false);
    chart.setBackgroundImageAlpha(0);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setBorderPaint(Color.LIGHT_GRAY);

    try {
        FileOutputStream fOut = new FileOutputStream(filePath);
        ChartUtilities.writeChartAsPNG(fOut, chart, 900, imageHeight);
        return fileName;
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:org.jfree.experimental.chart.plot.dial.DialTextAnnotation.java

/**
 * Draws the background to the specified graphics device.  If the dial
 * frame specifies a window, the clipping region will already have been 
 * set to this window before this method is called.
 *
 * @param g2  the graphics device (<code>null</code> not permitted).
 * @param plot  the plot (ignored here).
 * @param frame  the dial frame (ignored here).
 * @param view  the view rectangle (<code>null</code> not permitted). 
 *//* ww w.jav a  2 s  .c  o m*/
public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame, Rectangle2D view) {

    // work out the anchor point
    Rectangle2D f = DialPlot.rectangleByRadius(frame, this.radius, this.radius);
    Arc2D arc = new Arc2D.Double(f, this.angle, 0.0, Arc2D.OPEN);
    Point2D pt = arc.getStartPoint();
    g2.setPaint(this.paint);
    g2.setFont(this.font);
    TextUtilities.drawAlignedString(this.label, g2, (float) pt.getX(), (float) pt.getY(), this.anchor);

}