java.awt.geom.Rectangle2D Java Examples

The following examples show how to use java.awt.geom.Rectangle2D. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValueAxis.java    From ECG-Viewer with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Calculates the anchor point for a tick label.
 *
 * @param tick  the tick.
 * @param cursor  the cursor.
 * @param dataArea  the data area.
 * @param edge  the edge on which the axis is drawn.
 *
 * @return The x and y coordinates of the anchor point.
 */
protected float[] calculateAnchorPoint(ValueTick tick, double cursor,
        Rectangle2D dataArea, RectangleEdge edge) {

    RectangleInsets insets = getTickLabelInsets();
    float[] result = new float[2];
    if (edge == RectangleEdge.TOP) {
        result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);
        result[1] = (float) (cursor - insets.getBottom() - 2.0);
    }
    else if (edge == RectangleEdge.BOTTOM) {
        result[0] = (float) valueToJava2D(tick.getValue(), dataArea, edge);
        result[1] = (float) (cursor + insets.getTop() + 2.0);
    }
    else if (edge == RectangleEdge.LEFT) {
        result[0] = (float) (cursor - insets.getLeft() - 2.0);
        result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);
    }
    else if (edge == RectangleEdge.RIGHT) {
        result[0] = (float) (cursor + insets.getRight() + 2.0);
        result[1] = (float) valueToJava2D(tick.getValue(), dataArea, edge);
    }
    return result;
}
 
Example #2
Source File: LineNeedle.java    From SIMVA-SoS with Apache License 2.0 6 votes vote down vote up
/**
 * Draws the needle.
 *
 * @param g2  the graphics device.
 * @param plotArea  the plot area.
 * @param rotate  the rotation point.
 * @param angle  the angle.
 */
@Override
protected void drawNeedle(Graphics2D g2, Rectangle2D plotArea,
                          Point2D rotate, double angle) {

    Line2D shape = new Line2D.Double();

    double x = plotArea.getMinX() + (plotArea.getWidth() / 2);
    shape.setLine(x, plotArea.getMinY(), x, plotArea.getMaxY());

    Shape s = shape;

    if ((rotate != null) && (angle != 0)) {
        /// we have rotation
        getTransform().setToRotation(angle, rotate.getX(), rotate.getY());
        s = getTransform().createTransformedShape(s);
    }

    defaultDisplay(g2, s);

}
 
Example #3
Source File: Plot.java    From ECG-Viewer with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Draws a message to state that there is no data to plot.
 *
 * @param g2  the graphics device.
 * @param area  the area within which the plot should be drawn.
 */
protected void drawNoDataMessage(Graphics2D g2, Rectangle2D area) {
    Shape savedClip = g2.getClip();
    g2.clip(area);
    String message = this.noDataMessage;
    if (message != null) {
        g2.setFont(this.noDataMessageFont);
        g2.setPaint(this.noDataMessagePaint);
        TextBlock block = TextUtilities.createTextBlock(
                this.noDataMessage, this.noDataMessageFont,
                this.noDataMessagePaint, 0.9f * (float) area.getWidth(),
                new G2TextMeasurer(g2));
        block.draw(g2, (float) area.getCenterX(),
                (float) area.getCenterY(), TextBlockAnchor.CENTER);
    }
    g2.setClip(savedClip);
}
 
Example #4
Source File: MouseDraggedPaintableShape.java    From ghidra with Apache License 2.0 6 votes vote down vote up
public MouseDraggedPaintableShape(Point start, Point end, double tx, double ty) {
	super(tx, ty);
	this.color = new Color(200, 0, 80, 147);
	this.stroke = new BasicStroke(15);

	int x1 = start.x;
	int y1 = start.y;
	int x2 = end.x;
	int y2 = end.y;

	int w = Math.abs(x2 - x1);
	int h = Math.abs(y2 - y1);

	if (w == 0) {
		x2 += 1;
	}
	if (h == 0) {
		y2 += 1;
	}

	Rectangle2D rect = new Rectangle2D.Double(x1, y1, w, h);
	rect.setFrameFromDiagonal(x1, y1, x2, y2);
	rebuildPaint(start, end);
	this.shape = rect;
}
 
Example #5
Source File: CombinedDomainCategoryPlotTest.java    From ccu-historian with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check that only one chart change event is generated by a change to a
 * subplot.
 */
@Test
public void testNotification() {
    CombinedDomainCategoryPlot plot = createPlot();
    JFreeChart chart = new JFreeChart(plot);
    chart.addChangeListener(this);
    CategoryPlot subplot1 = (CategoryPlot) plot.getSubplots().get(0);
    NumberAxis yAxis = (NumberAxis) subplot1.getRangeAxis();
    yAxis.setAutoRangeIncludesZero(!yAxis.getAutoRangeIncludesZero());
    assertEquals(1, this.events.size());

    // a redraw should NOT trigger another change event
    BufferedImage image = new BufferedImage(200, 100,
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    this.events.clear();
    chart.draw(g2, new Rectangle2D.Double(0.0, 0.0, 200.0, 100.0));
    assertTrue(this.events.isEmpty());
}
 
Example #6
Source File: AbstractXYItemRenderer.java    From SIMVA-SoS with Apache License 2.0 6 votes vote down vote up
/**
 * Draws all the annotations for the specified layer.
 *
 * @param g2  the graphics device.
 * @param dataArea  the data area.
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param layer  the layer.
 * @param info  the plot rendering info.
 */
@Override
public void drawAnnotations(Graphics2D g2, Rectangle2D dataArea,
        ValueAxis domainAxis, ValueAxis rangeAxis, Layer layer,
        PlotRenderingInfo info) {

    Iterator iterator = null;
    if (layer.equals(Layer.FOREGROUND)) {
        iterator = this.foregroundAnnotations.iterator();
    }
    else if (layer.equals(Layer.BACKGROUND)) {
        iterator = this.backgroundAnnotations.iterator();
    }
    else {
        // should not get here
        throw new RuntimeException("Unknown layer.");
    }
    while (iterator.hasNext()) {
        XYAnnotation annotation = (XYAnnotation) iterator.next();
        int index = this.plot.getIndexOf(this);
        annotation.draw(g2, this.plot, dataArea, domainAxis, rangeAxis,
                index, info);
    }

}
 
Example #7
Source File: SubCategoryAxis.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the maximum of the relevant dimension (height or width) of the 
 * subcategory labels.
 * 
 * @param g2  the graphics device.
 * @param edge  the edge.
 * 
 * @return The maximum dimension.
 */
private double getMaxDim(Graphics2D g2, RectangleEdge edge) {
    double result = 0.0;
    g2.setFont(this.subLabelFont);
    FontMetrics fm = g2.getFontMetrics();
    Iterator iterator = this.subCategories.iterator();
    while (iterator.hasNext()) {
        Comparable subcategory = (Comparable) iterator.next();
        String label = subcategory.toString();
        Rectangle2D bounds = TextUtilities.getTextBounds(label, g2, fm);
        double dim = 0.0;
        if (RectangleEdge.isLeftOrRight(edge)) {
            dim = bounds.getWidth();   
        }
        else {  // must be top or bottom
            dim = bounds.getHeight();
        }
        result = Math.max(result, dim);
    }   
    return result;
}
 
Example #8
Source File: Plot.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Draws the background image (if there is one) aligned within the
 * specified area.
 *
 * @param g2  the graphics device.
 * @param area  the area.
 *
 * @see #getBackgroundImage()
 * @see #getBackgroundImageAlignment()
 * @see #getBackgroundImageAlpha()
 */
public void drawBackgroundImage(Graphics2D g2, Rectangle2D area) {
    if (this.backgroundImage == null) {
        return;  // nothing to do
    }
    Composite savedComposite = g2.getComposite();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
            this.backgroundImageAlpha));
    Rectangle2D dest = new Rectangle2D.Double(0.0, 0.0,
            this.backgroundImage.getWidth(null),
            this.backgroundImage.getHeight(null));
    Align.align(dest, area, this.backgroundImageAlignment);
    Shape savedClip = g2.getClip();
    g2.clip(area);
    g2.drawImage(this.backgroundImage, (int) dest.getX(),
            (int) dest.getY(), (int) dest.getWidth() + 1,
            (int) dest.getHeight() + 1, null);
    g2.setClip(savedClip);
    g2.setComposite(savedComposite);
}
 
Example #9
Source File: CombinedRangeCategoryPlotTest.java    From ccu-historian with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Check that only one chart change event is generated by a change to a
 * subplot.
 */
@Test
public void testNotification() {
    CombinedRangeCategoryPlot plot = createPlot();
    JFreeChart chart = new JFreeChart(plot);
    chart.addChangeListener(this);
    CategoryPlot subplot1 = (CategoryPlot) plot.getSubplots().get(0);
    NumberAxis yAxis = (NumberAxis) subplot1.getRangeAxis();
    yAxis.setAutoRangeIncludesZero(!yAxis.getAutoRangeIncludesZero());
    assertEquals(1, this.events.size());

    // a redraw should NOT trigger another change event
    BufferedImage image = new BufferedImage(200, 100,
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    this.events.clear();
    chart.draw(g2, new Rectangle2D.Double(0.0, 0.0, 200.0, 100.0));
    assertTrue(this.events.isEmpty());
}
 
Example #10
Source File: Cardumen_000_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Draws a line perpendicular to the range axis.
 *
 * @param g2  the graphics device.
 * @param plot  the plot.
 * @param axis  the value axis.
 * @param dataArea  the area for plotting data (not yet adjusted for any 3D
 *                  effect).
 * @param value  the value at which the grid line should be drawn.
 * @param paint  the paint (<code>null</code> not permitted).
 * @param stroke  the stroke (<code>null</code> not permitted).
 *
 * @see #drawRangeGridline
 *
 * @since 1.0.13
 */
public void drawRangeLine(Graphics2D g2, CategoryPlot plot, ValueAxis axis,
        Rectangle2D dataArea, double value, Paint paint, Stroke stroke) {

    Range range = axis.getRange();
    if (!range.contains(value)) {
        return;
    }

    PlotOrientation orientation = plot.getOrientation();
    Line2D line = null;
    double v = axis.valueToJava2D(value, dataArea, plot.getRangeAxisEdge());
    if (orientation == PlotOrientation.HORIZONTAL) {
        line = new Line2D.Double(v, dataArea.getMinY(), v,
                dataArea.getMaxY());
    }
    else if (orientation == PlotOrientation.VERTICAL) {
        line = new Line2D.Double(dataArea.getMinX(), v,
                dataArea.getMaxX(), v);
    }

    g2.setPaint(paint);
    g2.setStroke(stroke);
    g2.draw(line);

}
 
Example #11
Source File: Cardumen_0075_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Calculates the (x, y) coordinates for drawing a marker label.
 *
 * @param g2  the graphics device.
 * @param orientation  the plot orientation.
 * @param dataArea  the data area.
 * @param markerArea  the rectangle surrounding the marker.
 * @param markerOffset  the marker offset.
 * @param labelOffsetType  the label offset type.
 * @param anchor  the label anchor.
 *
 * @return The coordinates for drawing the marker label.
 */
protected Point2D calculateRangeMarkerTextAnchorPoint(Graphics2D g2,
                                  PlotOrientation orientation,
                                  Rectangle2D dataArea,
                                  Rectangle2D markerArea,
                                  RectangleInsets markerOffset,
                                  LengthAdjustmentType labelOffsetType,
                                  RectangleAnchor anchor) {

    Rectangle2D anchorRect = null;
    if (orientation == PlotOrientation.HORIZONTAL) {
        anchorRect = markerOffset.createAdjustedRectangle(markerArea,
                labelOffsetType, LengthAdjustmentType.CONTRACT);
    }
    else if (orientation == PlotOrientation.VERTICAL) {
        anchorRect = markerOffset.createAdjustedRectangle(markerArea,
                LengthAdjustmentType.CONTRACT, labelOffsetType);
    }
    return RectangleAnchor.coordinates(anchorRect, anchor);

}
 
Example #12
Source File: StandardXYItemRendererTest.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * A check to ensure that an item that falls outside the plot's data area
 * does NOT generate an item entity.
 */
@Test
public void testNoDisplayedItem() {
    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries s1 = new XYSeries("S1");
    s1.add(10.0, 10.0);
    dataset.addSeries(s1);
    JFreeChart chart = ChartFactory.createXYLineChart("Title", "X", "Y",
            dataset, PlotOrientation.VERTICAL, false, true, false);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setRenderer(new StandardXYItemRenderer());
    NumberAxis xAxis = (NumberAxis) plot.getDomainAxis();
    xAxis.setRange(0.0, 5.0);
    NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
    yAxis.setRange(0.0, 5.0);
    BufferedImage image = new BufferedImage(200 , 100,
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    ChartRenderingInfo info = new ChartRenderingInfo();
    chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, info);
    g2.dispose();
    EntityCollection ec = info.getEntityCollection();
    assertFalse(TestUtilities.containsInstanceOf(ec.getEntities(),
            XYItemEntity.class));
}
 
Example #13
Source File: PiePlotTests.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Draws a pie chart where the label generator returns null.
 */
public void testDrawWithNullLegendLabels() {
    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("L1", 12.0);
    dataset.setValue("L2", 11.0);
    JFreeChart chart = ChartFactory.createPieChart("Test", dataset, true, 
            false, false);
    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setLegendLabelGenerator(new NullLegendLabelGenerator());
    boolean success = false;
    try {
        BufferedImage image = new BufferedImage(200 , 100, 
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null);
        g2.dispose();
        success = true;
    }
    catch (Exception e) {
      success = false;
    }
    assertTrue(success);
}
 
Example #14
Source File: SymbolAxis.java    From ECG-Viewer with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Calculates the positions of the tick labels for the axis, storing the
 * results in the tick label list (ready for drawing).
 *
 * @param g2  the graphics device.
 * @param state  the axis state.
 * @param dataArea  the area in which the data should be drawn.
 * @param edge  the location of the axis.
 *
 * @return A list of ticks.
 */
@Override
public List refreshTicks(Graphics2D g2, AxisState state,
        Rectangle2D dataArea, RectangleEdge edge) {
    List ticks = null;
    if (RectangleEdge.isTopOrBottom(edge)) {
        ticks = refreshTicksHorizontal(g2, dataArea, edge);
    } else if (RectangleEdge.isLeftOrRight(edge)) {
        ticks = refreshTicksVertical(g2, dataArea, edge);
    }
    return ticks;
}
 
Example #15
Source File: DrawingPlugin.java    From depan with Apache License 2.0 5 votes vote down vote up
private void updateDrawingBounds(Rectangle2D bounds) {
  if (null == drawingBounds) {
    drawingBounds = bounds.getBounds2D();
    return;
  }
  drawingBounds.add(bounds);
}
 
Example #16
Source File: FreetypeFontScaler.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
synchronized Rectangle2D.Float getGlyphOutlineBounds(
                 long pScalerContext, int glyphCode)
                 throws FontScalerException {
    if (nativeScaler != 0L) {
        return getGlyphOutlineBoundsNative(font.get(),
                                           pScalerContext,
                                           nativeScaler,
                                           glyphCode);
    }
    return FontScaler.getNullScaler().
        getGlyphOutlineBounds(0L,glyphCode);
}
 
Example #17
Source File: NamedTabbedPaneTabAreaPainter.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
private Rectangle2D decodeRect2() {
    rect.setRect(decodeX(0.0f), //x
            decodeY(2.1666667f), //y
            decodeX(3.0f) - decodeX(0.0f), //width
            decodeY(3.0f) - decodeY(2.1666667f)); //height
    return rect;
}
 
Example #18
Source File: LineChart3DTest.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Draws the chart with a null info object to make sure that no exceptions
 * are thrown (a problem that was occurring at one point).
 */
@Test
public void testDrawWithNullInfo() {

    BufferedImage image = new BufferedImage(200 , 100,
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    this.chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null,
            null);
    g2.dispose();
    //FIXME we should really assert a value here
}
 
Example #19
Source File: NamedTabbedPaneTabAreaPainter.java    From bither-desktop-java with Apache License 2.0 5 votes vote down vote up
private Rectangle2D decodeRect1() {
    rect.setRect(decodeX(0.0f), //x
            decodeY(1.0f), //y
            decodeX(0.0f) - decodeX(0.0f), //width
            decodeY(1.0f) - decodeY(1.0f)); //height
    return rect;
}
 
Example #20
Source File: JFreeChart.java    From SIMVA-SoS with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a rectangle that is aligned to the frame.
 *
 * @param dimensions  the dimensions for the rectangle.
 * @param frame  the frame to align to.
 * @param hAlign  the horizontal alignment.
 * @param vAlign  the vertical alignment.
 *
 * @return A rectangle.
 */
private Rectangle2D createAlignedRectangle2D(Size2D dimensions,
        Rectangle2D frame, HorizontalAlignment hAlign,
        VerticalAlignment vAlign) {
    double x = Double.NaN;
    double y = Double.NaN;
    if (hAlign == HorizontalAlignment.LEFT) {
        x = frame.getX();
    }
    else if (hAlign == HorizontalAlignment.CENTER) {
        x = frame.getCenterX() - (dimensions.width / 2.0);
    }
    else if (hAlign == HorizontalAlignment.RIGHT) {
        x = frame.getMaxX() - dimensions.width;
    }
    if (vAlign == VerticalAlignment.TOP) {
        y = frame.getY();
    }
    else if (vAlign == VerticalAlignment.CENTER) {
        y = frame.getCenterY() - (dimensions.height / 2.0);
    }
    else if (vAlign == VerticalAlignment.BOTTOM) {
        y = frame.getMaxY() - dimensions.height;
    }

    return new Rectangle2D.Double(x, y, dimensions.width,
            dimensions.height);
}
 
Example #21
Source File: MultiTextUI.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Rectangle2D modelToView2D(JTextComponent a, int b, Position.Bias c) throws BadLocationException {
    Rectangle2D returnValue =
        ((TextUI) (uis.elementAt(0))).modelToView2D(a,b,c);
    for (int i = 1; i < uis.size(); i++) {
        ((TextUI) (uis.elementAt(i))).modelToView2D(a,b,c);
    }
    return returnValue;
}
 
Example #22
Source File: StandardWorldModel.java    From rcrs-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
   Get the world bounds.
   @return A Rectangle2D describing the bounds of the world.
*/
public Rectangle2D getBounds() {
    if (!indexed) {
        index();
    }
    return new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY);
}
 
Example #23
Source File: LevelRenderer.java    From SIMVA-SoS with Apache License 2.0 5 votes vote down vote up
/**
 * Calculates the bar width and stores it in the renderer state.
 *
 * @param plot  the plot.
 * @param dataArea  the data area.
 * @param rendererIndex  the renderer index.
 * @param state  the renderer state.
 */
protected void calculateItemWidth(CategoryPlot plot,
        Rectangle2D dataArea, int rendererIndex,
        CategoryItemRendererState state) {

    CategoryAxis domainAxis = getDomainAxis(plot, rendererIndex);
    CategoryDataset dataset = plot.getDataset(rendererIndex);
    if (dataset != null) {
        int columns = dataset.getColumnCount();
        int rows = state.getVisibleSeriesCount() >= 0
                ? state.getVisibleSeriesCount() : dataset.getRowCount();
        double space = 0.0;
        PlotOrientation orientation = plot.getOrientation();
        if (orientation == PlotOrientation.HORIZONTAL) {
            space = dataArea.getHeight();
        }
        else if (orientation == PlotOrientation.VERTICAL) {
            space = dataArea.getWidth();
        }
        double maxWidth = space * getMaximumItemWidth();
        double categoryMargin = 0.0;
        double currentItemMargin = 0.0;
        if (columns > 1) {
            categoryMargin = domainAxis.getCategoryMargin();
        }
        if (rows > 1) {
            currentItemMargin = getItemMargin();
        }
        double used = space * (1 - domainAxis.getLowerMargin()
                                 - domainAxis.getUpperMargin()
                                 - categoryMargin - currentItemMargin);
        if ((rows * columns) > 0) {
            state.setBarWidth(Math.min(used / (rows * columns), maxWidth));
        }
        else {
            state.setBarWidth(Math.min(used, maxWidth));
        }
    }
}
 
Example #24
Source File: Plot2D.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void drawPolylineError(Graphics2D g, PolylineErrorShape aPLS, PointBreak aPB, Rectangle2D area) {
    for (Polyline aline : aPLS.getPolylines()) {
        double[] sXY;
        PointF p;
        double error;
        double elen = 6;
        g.setColor(aPB.getColor());
        for (int i = 0; i < aline.getPointList().size(); i++) {
            PointD wPoint = aline.getPointList().get(i);
            sXY = projToScreen(wPoint.X, wPoint.Y, area);
            p = new PointF((float) sXY[0], (float) sXY[1]);
            if (aPLS.getYerror() != null) {
                error = aPLS.getYerror(i);
                error = this.projYLength(error, area);
                g.draw(new Line2D.Double(p.X, p.Y - error, p.X, p.Y + error));
                g.draw(new Line2D.Double(p.X - (elen * 0.5), p.Y - error, p.X + (elen * 0.5), p.Y - error));
                g.draw(new Line2D.Double(p.X - (elen * 0.5), p.Y + error, p.X + (elen * 0.5), p.Y + error));
            }
            if (aPLS.getXerror() != null) {
                error = aPLS.getXerror(i);
                error = this.projXLength(error, area);
                g.draw(new Line2D.Double(p.X - error, p.Y, p.X + error, p.Y));
                g.draw(new Line2D.Double(p.X - error, p.Y - (elen * 0.5), p.X - error, p.Y + (elen * 0.5)));
                g.draw(new Line2D.Double(p.X + error, p.Y - (elen * 0.5), p.X + error, p.Y + (elen * 0.5)));
            }
            Draw.drawPoint(p, aPB, g);
        }
    }
}
 
Example #25
Source File: GraphicsUtils.java    From tensorflow with Apache License 2.0 5 votes vote down vote up
/**
 * Augments the input image with a labeled rectangle (e.g. bounding box) with coordinates: (x1, y1, x2, y2).
 *
 * @param image Input image to be augmented with labeled rectangle.
 * @param cid Unique id used to select the color of the rectangle. Used only if the colorAgnostic is set to false.
 * @param title rectangle title
 * @param x1 top left corner for the bounding box
 * @param y1 top left corner for the bounding box
 * @param x2 bottom right corner for the bounding box
 * @param y2 bottom right corner for the bounding box
 * @param colorAgnostic If set to false the cid is used to select the bounding box color. Uses the
 *                      AGNOSTIC_COLOR otherwise.
 */
public static void drawBoundingBox(BufferedImage image, int cid, String title, int x1, int y1, int x2, int y2,
		boolean colorAgnostic) {

	Graphics2D g = image.createGraphics();
	g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

	Color labelColor = colorAgnostic ? AGNOSTIC_COLOR : GraphicsUtils.getClassColor(cid);
	g.setColor(labelColor);

	g.setFont(DEFAULT_FONT);
	FontMetrics fontMetrics = g.getFontMetrics();

	Stroke oldStroke = g.getStroke();
	g.setStroke(new BasicStroke(LINE_THICKNESS));
	g.drawRect(x1, y1, (x2 - x1), (y2 - y1));
	g.setStroke(oldStroke);

	Rectangle2D rect = fontMetrics.getStringBounds(title, g);

	g.setColor(labelColor);
	g.fillRect(x1, y1 - fontMetrics.getAscent(),
			(int) rect.getWidth() + 2 * TITLE_OFFSET, (int) rect.getHeight());

	g.setColor(getTextColor(labelColor));
	g.drawString(title, x1 + TITLE_OFFSET, y1);
}
 
Example #26
Source File: GridWorldVisualizer.java    From burlap with Apache License 2.0 5 votes vote down vote up
@Override
public void paintObject(Graphics2D g2, OOState s, ObjectInstance ob, float cWidth, float cHeight) {
	
	int type = (Integer)ob.get(VAR_TYPE);
	int multiplier = type / this.baseColors.size();
	int colIndex = type % this.baseColors.size();
	
	Color col = this.baseColors.get(colIndex);
	for(int i = 0; i < multiplier; i++){
		col = col.darker();
	}
	
	//set the color of the object
	g2.setColor(col);
	
	float domainXScale = this.dwidth;
	float domainYScale = this.dheight;
	
	//determine then normalized width
	float width = (1.0f / domainXScale) * cWidth;
	float height = (1.0f / domainYScale) * cHeight;

	float rx = (Integer)ob.get(VAR_X)*width;
	float ry = cHeight - height - (Integer)ob.get(VAR_Y)*height;

	
	g2.fill(new Rectangle2D.Float(rx, ry, width, height));
	
}
 
Example #27
Source File: SunGraphics2D.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
Shape intersectRectShape(Rectangle2D r, Shape s,
                         boolean keep1, boolean keep2) {
    if (s instanceof Rectangle2D) {
        Rectangle2D r2 = (Rectangle2D) s;
        Rectangle2D outrect;
        if (!keep1) {
            outrect = r;
        } else if (!keep2) {
            outrect = r2;
        } else {
            outrect = new Rectangle2D.Float();
        }
        double x1 = Math.max(r.getX(), r2.getX());
        double x2 = Math.min(r.getX()  + r.getWidth(),
                             r2.getX() + r2.getWidth());
        double y1 = Math.max(r.getY(), r2.getY());
        double y2 = Math.min(r.getY()  + r.getHeight(),
                             r2.getY() + r2.getHeight());

        if (((x2 - x1) < 0) || ((y2 - y1) < 0))
            // Width or height is negative. No intersection.
            outrect.setFrameFromDiagonal(0, 0, 0, 0);
        else
            outrect.setFrameFromDiagonal(x1, y1, x2, y2);
        return outrect;
    }
    if (r.contains(s.getBounds2D())) {
        if (keep2) {
            s = cloneShape(s);
        }
        return s;
    }
    return intersectByArea(r, s, keep1, keep2);
}
 
Example #28
Source File: Axis.java    From ccu-historian with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a rectangle that encloses the axis label.  This is typically
 * used for layout purposes (it gives the maximum dimensions of the label).
 *
 * @param g2  the graphics device.
 * @param edge  the edge of the plot area along which the axis is measuring.
 *
 * @return The enclosing rectangle.
 */
protected Rectangle2D getLabelEnclosure(Graphics2D g2, RectangleEdge edge) {
    Rectangle2D result = new Rectangle2D.Double();
    Rectangle2D bounds = null;
    if (this.attributedLabel != null) {
        TextLayout layout = new TextLayout(
                this.attributedLabel.getIterator(), 
                g2.getFontRenderContext());
        bounds = layout.getBounds();
    } else {
        String axisLabel = getLabel();
        if (axisLabel != null && !axisLabel.equals("")) {
            FontMetrics fm = g2.getFontMetrics(getLabelFont());
            bounds = TextUtilities.getTextBounds(axisLabel, g2, fm);
        }
    }
    if (bounds != null) {
        RectangleInsets insets = getLabelInsets();
        bounds = insets.createOutsetRectangle(bounds);
        double angle = getLabelAngle();
        if (edge == RectangleEdge.LEFT || edge == RectangleEdge.RIGHT) {
            angle = angle - Math.PI / 2.0;
        }
        double x = bounds.getCenterX();
        double y = bounds.getCenterY();
        AffineTransform transformer
            = AffineTransform.getRotateInstance(angle, x, y);
        Shape labelBounds = transformer.createTransformedShape(bounds);
        result = labelBounds.getBounds2D();
    }
    return result;
}
 
Example #29
Source File: MeterPlot.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fills an arc on the dial between the given values.
 *
 * @param g2  the graphics device.
 * @param area  the plot area.
 * @param minValue  the minimum data value.
 * @param maxValue  the maximum data value.
 * @param paint  the background paint (<code>null</code> not permitted).
 * @param dial  a flag that indicates whether the arc represents the whole
 *              dial.
 */
protected void fillArc(Graphics2D g2, Rectangle2D area,
        double minValue, double maxValue, Paint paint, boolean dial) {

    ParamChecks.nullNotPermitted(paint, "paint");
    double startAngle = valueToAngle(maxValue);
    double endAngle = valueToAngle(minValue);
    double extent = endAngle - startAngle;

    double x = area.getX();
    double y = area.getY();
    double w = area.getWidth();
    double h = area.getHeight();
    int joinType = Arc2D.OPEN;
    if (this.shape == DialShape.PIE) {
        joinType = Arc2D.PIE;
    }
    else if (this.shape == DialShape.CHORD) {
        if (dial && this.meterAngle > 180) {
            joinType = Arc2D.CHORD;
        }
        else {
            joinType = Arc2D.PIE;
        }
    }
    else if (this.shape == DialShape.CIRCLE) {
        joinType = Arc2D.PIE;
        if (dial) {
            extent = 360;
        }
    }
    else {
        throw new IllegalStateException("DialShape not recognised.");
    }

    g2.setPaint(paint);
    Arc2D.Double arc = new Arc2D.Double(x, y, w, h, startAngle, extent,
            joinType);
    g2.fill(arc);
}
 
Example #30
Source File: CategoryAxis.java    From openstock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Draws the axis on a Java 2D graphics device (such as the screen or a
 * printer).
 *
 * @param g2  the graphics device (<code>null</code> not permitted).
 * @param cursor  the cursor location.
 * @param plotArea  the area within which the axis should be drawn
 *                  (<code>null</code> not permitted).
 * @param dataArea  the area within which the plot is being drawn
 *                  (<code>null</code> not permitted).
 * @param edge  the location of the axis (<code>null</code> not permitted).
 * @param plotState  collects information about the plot
 *                   (<code>null</code> permitted).
 *
 * @return The axis state (never <code>null</code>).
 */
@Override
public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
        Rectangle2D dataArea, RectangleEdge edge,
        PlotRenderingInfo plotState) {

    // if the axis is not visible, don't draw it...
    if (!isVisible()) {
        return new AxisState(cursor);
    }

    if (isAxisLineVisible()) {
        drawAxisLine(g2, cursor, dataArea, edge);
    }
    AxisState state = new AxisState(cursor);
    if (isTickMarksVisible()) {
        drawTickMarks(g2, cursor, dataArea, edge, state);
    }

    createAndAddEntity(cursor, state, dataArea, edge, plotState);

    // draw the category labels and axis label
    state = drawCategoryLabels(g2, plotArea, dataArea, edge, state,
            plotState);
    if (getAttributedLabel() != null) {
        state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, 
                dataArea, edge, state);
        
    } else {
        state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);
    }
    return state;

}