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: 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 #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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #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: 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 #11
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 #12
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 #13
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 #14
Source File: ProcessDrawUtils.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Draws a shadow around the given rectangle.
 *
 * @param rect
 * 		the rectangle which should get a shadow
 * @param g2
 * 		the graphics context to draw the shadow on
 */
public static void drawShadow(final Rectangle2D rect, final Graphics2D g2) {
	Graphics2D g2S = (Graphics2D) g2.create();

	Rectangle2D shadow = new Rectangle2D.Double(rect.getX() + 5, rect.getY() + ProcessDrawer.HEADER_HEIGHT + 5,
			rect.getWidth(), rect.getHeight() - ProcessDrawer.HEADER_HEIGHT);
	GeneralPath bottom = new GeneralPath();
	bottom.moveTo(shadow.getX(), rect.getMaxY());
	bottom.lineTo(rect.getMaxX(), rect.getMaxY());
	bottom.lineTo(shadow.getMaxX(), shadow.getMaxY());
	bottom.lineTo(shadow.getMinX(), shadow.getMaxY());
	bottom.closePath();
	g2S.setPaint(new GradientPaint((float) rect.getX(), (float) rect.getMaxY(), Color.gray, (float) rect.getX(),
			(float) shadow.getMaxY(), TRANSPARENT_GRAY));
	g2S.fill(bottom);

	GeneralPath right = new GeneralPath();
	right.moveTo(rect.getMaxX(), shadow.getMinY());
	right.lineTo(shadow.getMaxX(), shadow.getMinY());
	right.lineTo(shadow.getMaxX(), shadow.getMaxY());
	right.lineTo(rect.getMaxX(), rect.getMaxY());
	right.closePath();
	g2S.setPaint(new GradientPaint((float) rect.getMaxX(), (float) shadow.getY(), Color.gray, (float) shadow.getMaxX(),
			(float) shadow.getY(), TRANSPARENT_GRAY));
	g2S.fill(right);

	g2S.dispose();
}
 
Example #15
Source File: TimeSeriesChartTest.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() {
    try {
        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();
    }
    catch (Exception e) {
      fail("No exception should be triggered.");
    }
}
 
Example #16
Source File: AffineTransformOp.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the bounding box of the transformed destination.  The
 * rectangle returned will be the actual bounding box of the
 * transformed points.  The coordinates of the upper-left corner
 * of the returned rectangle might not be (0,&nbsp;0).
 *
 * @param src The <CODE>Raster</CODE> to be transformed.
 *
 * @return The <CODE>Rectangle2D</CODE> representing the destination's
 * bounding box.
 */
public final Rectangle2D getBounds2D (Raster src) {
    int w = src.getWidth();
    int h = src.getHeight();

    // Get the bounding box of the src and transform the corners
    float[] pts = {0, 0, w, 0, w, h, 0, h};
    xform.transform(pts, 0, pts, 0, 4);

    // Get the min, max of the dst
    float fmaxX = pts[0];
    float fmaxY = pts[1];
    float fminX = pts[0];
    float fminY = pts[1];
    for (int i=2; i < 8; i+=2) {
        if (pts[i] > fmaxX) {
            fmaxX = pts[i];
        }
        else if (pts[i] < fminX) {
            fminX = pts[i];
        }
        if (pts[i+1] > fmaxY) {
            fmaxY = pts[i+1];
        }
        else if (pts[i+1] < fminY) {
            fminY = pts[i+1];
        }
    }

    return new Rectangle2D.Float(fminX, fminY, fmaxX-fminX, fmaxY-fminY);
}
 
Example #17
Source File: BoundingBoxHelper.java    From workcraft with MIT License 5 votes vote down vote up
public static Rectangle2D expand(Rectangle2D rect, double x, double y) {
    Rectangle2D result = null;
    if (rect != null) {
        result = new Rectangle2D.Double();
        result.setRect(rect);
        x /= 2.0f;
        y /= 2.0f;
        result.add(rect.getMinX() - x, rect.getMinY() - y);
        result.add(rect.getMaxX() + x, rect.getMaxY() + y);
    }
    return result;
}
 
Example #18
Source File: FXGraphics2DDemo1.java    From jfree-fxdemos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void draw() { 
    double width = getWidth(); 
    double height = getHeight();
    getGraphicsContext2D().clearRect(0, 0, width, height);
    this.chart.draw(this.g2, new Rectangle2D.Double(0, 0, width, 
            height));
}
 
Example #19
Source File: AlignAction.java    From openAGV with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the bounds of the selected figures.
 */
protected Rectangle2D.Double getSelectionBounds() {
  Rectangle2D.Double bounds = null;

  for (Figure f : getView().getSelectedFigures()) {
    if (bounds == null) {
      bounds = f.getBounds();
    }
    else {
      bounds.add(f.getBounds());
    }
  }

  return bounds;
}
 
Example #20
Source File: GlyphPainter2.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
public Shape modelToView(GlyphView v, int pos, Position.Bias bias,
                         Shape a) throws BadLocationException {
    int offs = pos - v.getStartOffset();
    Rectangle2D alloc = a.getBounds2D();
    TextHitInfo hit = (bias == Position.Bias.Forward) ?
        TextHitInfo.afterOffset(offs) : TextHitInfo.beforeOffset(offs);
    float[] locs = layout.getCaretInfo(hit);

    // vertical at the baseline, should use slope and check if glyphs
    // are being rendered vertically.
    Rectangle2D rect = new Rectangle2D.Float();
    rect.setRect(alloc.getX() + locs[0], alloc.getY(), 1, alloc.getHeight());
    return rect;
}
 
Example #21
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 #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
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;
}