Java Code Examples for java.awt.geom.Point2D

The following examples show how to use java.awt.geom.Point2D. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: coming   Source File: Cardumen_0075_s.java    License: MIT License 6 votes vote down vote up
/**
 * Calculates the (x, y) coordinates for drawing the label for a marker on
 * the range axis.
 *
 * @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 calculateDomainMarkerTextAnchorPoint(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,
                LengthAdjustmentType.CONTRACT, labelOffsetType);
    }
    else if (orientation == PlotOrientation.VERTICAL) {
        anchorRect = markerOffset.createAdjustedRectangle(markerArea,
                labelOffsetType, LengthAdjustmentType.CONTRACT);
    }
    return RectangleAnchor.coordinates(anchorRect, anchor);

}
 
Example 2
Source Project: netbeans   Source File: ConnectionWidget.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns an index of a control point that is hit by the local location
 * @param localLocation the local location
 * @return the index; -1 if no control point was hit
 */
public final int getControlPointHitAt (Point localLocation) {
    int controlRadius = controlPointShape.getRadius ();
    controlRadius *= controlRadius;

    if (isFirstControlPointHitAt (localLocation))
        return 0;

    if (isLastControlPointHitAt (localLocation))
        return controlPoints.size () - 1;

    for (int i = 0; i < controlPoints.size (); i ++) {
        Point point = controlPoints.get (i);
        if (Point2D.distanceSq (point.x, point.y, localLocation.x, localLocation.y) <= controlRadius)
            return i;
    }

    return -1;
}
 
Example 3
Source Project: workcraft   Source File: HitMan.java    License: MIT License 6 votes vote down vote up
public static Node hitFirstChild(Point2D point, Node parentNode, Func<Node, Boolean> filter) {
    Node result = null;
    Point2D pointInLocalSpace = transformToChildSpace(point, parentNode);
    for (Node childNode : getHitableChildrenInReverseOrder(parentNode)) {
        if (filter.eval(childNode)) {
            Node branchNode = hitBranch(pointInLocalSpace, childNode);
            if (filter.eval(branchNode)) {
                result = branchNode;
            }
        } else {
            result = hitFirstChild(pointInLocalSpace, childNode, filter);
        }
        if (result != null) break;
    }
    return result;
}
 
Example 4
Source Project: Freerouting   Source File: GraphicsContext.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void draw_rectangle(FloatPoint p_corner1, FloatPoint p_corner2,
        double p_draw_half_width, Color p_color,  Graphics p_g, double p_translucency_factor)
{
    if (p_color == null)
    {
        return;
    }
    Graphics2D g2 = (Graphics2D)p_g ;
    Point2D corner1 = coordinate_transform.board_to_screen(p_corner1) ;
    Point2D corner2 = coordinate_transform.board_to_screen(p_corner2) ;
    
    double xmin = Math.min(corner1.getX(), corner2.getX()) ;
    double ymin = Math.min(corner1.getY(), corner2.getY()) ;
    
    float draw_width = (float)(2 * coordinate_transform.board_to_screen(p_draw_half_width)) ;
    double width = Math.abs(corner2.getX() - corner1.getX()) ;
    double height = Math.abs(corner2.getY() - corner1.getY()) ;
    Rectangle2D rectangle = new Rectangle2D.Double(xmin, ymin, width, height) ;
    set_translucency(g2, p_translucency_factor);
    init_draw_graphics(g2, p_color, draw_width) ;
    g2.draw(rectangle) ;
}
 
Example 5
Source Project: easytable   Source File: TableDrawer.java    License: MIT License 6 votes vote down vote up
protected void drawRow(Point2D.Float start, Row row, int rowIndex, BiConsumer<Drawer, DrawingContext> consumer) {
    float x = start.x;

    int columnCounter = 0;
    for (AbstractCell cell : row.getCells()) {

        while (table.isRowSpanAt(rowIndex, columnCounter)) {
            x += table.getColumns().get(columnCounter).getWidth();
            columnCounter++;
        }

        // This is the interesting part :)
        consumer.accept(
                cell.getDrawer(),
                new DrawingContext(
                        contentStream, page, new Point2D.Float(x, start.y)
                )
        );

        x += cell.getWidth();
        columnCounter += cell.getColSpan();
    }
}
 
Example 6
Source Project: buffer_bci   Source File: DialPointer.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Draws the pointer.
 *
 * @param g2  the graphics target.
 * @param plot  the plot.
 * @param frame  the dial's reference frame.
 * @param view  the dial's view.
 */
@Override
public void draw(Graphics2D g2, DialPlot plot, Rectangle2D frame,
    Rectangle2D view) {

    g2.setPaint(this.paint);
    g2.setStroke(this.stroke);
    Rectangle2D arcRect = DialPlot.rectangleByRadius(frame,
            this.radius, this.radius);

    double value = plot.getValue(this.datasetIndex);
    DialScale scale = plot.getScaleForDataset(this.datasetIndex);
    double angle = scale.valueToAngle(value);

    Arc2D arc = new Arc2D.Double(arcRect, angle, 0, Arc2D.OPEN);
    Point2D pt = arc.getEndPoint();

    Line2D line = new Line2D.Double(frame.getCenterX(),
            frame.getCenterY(), pt.getX(), pt.getY());
    g2.draw(line);
}
 
Example 7
Source Project: openstock   Source File: OutlierTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * A test for the equals() method.
 */
@Test
public void testEquals() {
    Outlier out1 = new Outlier(1.0, 2.0, 3.0);
    Outlier out2 = new Outlier(1.0, 2.0, 3.0);
    assertTrue(out1.equals(out2));
    assertTrue(out2.equals(out1));

    out1.setPoint(new Point2D.Double(2.0, 2.0));
    assertFalse(out1.equals(out2));
    out2.setPoint(new Point2D.Double(2.0, 2.0));
    assertTrue(out1.equals(out2));

    out1.setPoint(new Point2D.Double(2.0, 3.0));
    assertFalse(out1.equals(out2));
    out2.setPoint(new Point2D.Double(2.0, 3.0));
    assertTrue(out1.equals(out2));

    out1.setRadius(4.0);
    assertFalse(out1.equals(out2));
    out2.setRadius(4.0);
    assertTrue(out1.equals(out2));
}
 
Example 8
Source Project: depan   Source File: ArcBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private Point2D findBoundary(
    GLEntity shape, Point2D point1, Point2D point2) {
  Vec2 vec1 = new Vec2(point1);
  Vec2 vec2 = new Vec2(point2);
  Vec2 dir = vec2.minus(vec1);
  float shift = 0.5f;
  Vec2 move = dir.mult(shift);
  while (move.length() > AWTShape.lineFlatness) {
    vec1 = vec1.plus(move);
    shift = shift * 0.5f;
    if (shape.contains(vec1.x, vec1.y)) {
      move = dir.mult(shift);
    } else {
      move = dir.mult(- shift);
    }
  }

  return new Point2D.Double(vec1.x, vec1.y);
}
 
Example 9
Source Project: openstock   Source File: PiePlot.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns a rectangle that can be used to create a pie section (taking
 * into account the amount by which the pie section is 'exploded').
 *
 * @param unexploded  the area inside which the unexploded pie sections are
 *                    drawn.
 * @param exploded  the area inside which the exploded pie sections are
 *                  drawn.
 * @param angle  the start angle.
 * @param extent  the extent of the arc.
 * @param explodePercent  the amount by which the pie section is exploded.
 *
 * @return A rectangle that can be used to create a pie section.
 */
protected Rectangle2D getArcBounds(Rectangle2D unexploded,
                                   Rectangle2D exploded,
                                   double angle, double extent,
                                   double explodePercent) {

    if (explodePercent == 0.0) {
        return unexploded;
    }
    Arc2D arc1 = new Arc2D.Double(unexploded, angle, extent / 2,
            Arc2D.OPEN);
    Point2D point1 = arc1.getEndPoint();
    Arc2D.Double arc2 = new Arc2D.Double(exploded, angle, extent / 2,
            Arc2D.OPEN);
    Point2D point2 = arc2.getEndPoint();
    double deltaX = (point1.getX() - point2.getX()) * explodePercent;
    double deltaY = (point1.getY() - point2.getY()) * explodePercent;
    return new Rectangle2D.Double(unexploded.getX() - deltaX,
            unexploded.getY() - deltaY, unexploded.getWidth(),
            unexploded.getHeight());
}
 
Example 10
short Routine_label_200(//Graphics g
                        List<LinkedList<Point2D>> allPaths
        , boolean workSpace[]) {
    while (true) {
        xy[elle] = 1.0 * ij[elle] + intersect[iedge - 1];
        xy[1 - elle] = 1.0 * ij[1 - elle];
        workSpace[2 * (xSteps * (ySteps * cntrIndex + ij[1] - 1)
                + ij[0] - 1) + elle] = true;
        DrawKernel(allPaths);
        if (iflag >= 4) {
            icur = ij[0];
            jcur = ij[1];
            return 1;
        }
        ContinueContour();
        if (!workSpace[2 * (xSteps * (ySteps * cntrIndex
                + ij[1] - 1) + ij[0] - 1) + elle]) return 2;
        iflag = 5;                    // 5. Finish a closed contour
        iedge = ks + 2;
        if (iedge > 4) iedge = iedge - 4;
        intersect[iedge - 1] = intersect[ks - 1];
    }
}
 
Example 11
private void configurePageFooter()
{
  final PageFooter pageFooter = report.getPageFooter();
  final ElementStyleSheet style = pageFooter.getStyle();
  style.setStyleProperty(BandStyleKeys.DISPLAY_ON_FIRSTPAGE, Boolean.TRUE);
  style.setStyleProperty(ElementStyleKeys.MIN_HEIGHT, new Float(24));
  style.setStyleProperty(ElementStyleKeys.BACKGROUND_COLOR, new Color(0xAFAFAF));
  pageFooter.addElement
      (HorizontalLineElementFactory.createHorizontalLine
          (0, null, new BasicStroke(1)));

  final TextFieldElementFactory elementFactory = new TextFieldElementFactory();
  elementFactory.setAbsolutePosition(new Point2D.Float(0, 4));
  elementFactory.setMinimumSize(new FloatDimension(-100, -100));
  elementFactory.setVerticalAlignment(ElementAlignment.MIDDLE);
  elementFactory.setHorizontalAlignment(ElementAlignment.RIGHT);
  elementFactory.setFieldname("pageXofY");
  report.getPageFooter().addElement(elementFactory.createElement());
}
 
Example 12
/**
 * Multiplies the range on the range axis/axes by the specified factor.
 *
 * @param factor  the zoom factor.
 * @param info  the plot rendering info (<code>null</code> not permitted).
 * @param source  the source point (<code>null</code> not permitted).
 * @param useAnchor  zoom about the anchor point?
 */
@Override
public void zoomRangeAxes(double factor, PlotRenderingInfo info,
                          Point2D source, boolean useAnchor) {
    // delegate 'info' and 'source' argument checks...
    CategoryPlot subplot = findSubplot(info, source);
    if (subplot != null) {
        subplot.zoomRangeAxes(factor, info, source, useAnchor);
    }
    else {
        // if the source point doesn't fall within a subplot, we do the
        // zoom on all subplots...
        Iterator iterator = getSubplots().iterator();
        while (iterator.hasNext()) {
            subplot = (CategoryPlot) iterator.next();
            subplot.zoomRangeAxes(factor, info, source, useAnchor);
        }
    }
}
 
Example 13
Source Project: ghidra   Source File: AbstractVisualGraphLayout.java    License: Apache License 2.0 6 votes vote down vote up
private Map<V, Point2D> positionVerticesInLayoutSpace(
		VisualGraphVertexShapeTransformer<V> transformer, Collection<V> vertices,
		LayoutLocationMap<V, E> layoutLocations) throws CancelledException {
	// use the calculated row and column sizes to place the vertices in
	// their final positions (including x and y from bounds 'cause they're
	// centered)
	Map<V, Point2D> newLocations = new HashMap<>();
	for (V vertex : vertices) {
		monitor.checkCanceled();

		Row<V> row = layoutLocations.row(vertex);
		Column column = layoutLocations.col(vertex);

		Shape shape = transformer.apply(vertex);
		Rectangle bounds = shape.getBounds();
		Point2D location = getVertexLocation(vertex, column, row, bounds);
		newLocations.put(vertex, location);
	}
	return newLocations;
}
 
Example 14
Source Project: astor   Source File: ShapeUtilities.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Translates a shape to a new location such that the anchor point
 * (relative to the rectangular bounds of the shape) aligns with the
 * specified (x, y) coordinate in Java2D space.
 *
 * @param shape  the shape (<code>null</code> not permitted).
 * @param anchor  the anchor (<code>null</code> not permitted).
 * @param locationX  the x-coordinate (in Java2D space).
 * @param locationY  the y-coordinate (in Java2D space).
 *
 * @return A new and translated shape.
 */
public static Shape createTranslatedShape(Shape shape,
                                          RectangleAnchor anchor,
                                          double locationX,
                                          double locationY) {
    if (shape == null) {
        throw new IllegalArgumentException("Null 'shape' argument.");
    }
    if (anchor == null) {
        throw new IllegalArgumentException("Null 'anchor' argument.");
    }
    Point2D anchorPoint = RectangleAnchor.coordinates(shape.getBounds2D(),
            anchor);
    AffineTransform transform = AffineTransform.getTranslateInstance(
            locationX - anchorPoint.getX(), locationY - anchorPoint.getY());
    return transform.createTransformedShape(shape);
}
 
Example 15
Source Project: testarea-pdfbox2   Source File: PDFVisibleTextStripper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(Operator operator, List<COSBase> operands) throws IOException {
    if (operands.size() < 6) {
        throw new MissingOperandException(operator, operands);
    }
    if (!checkArrayTypesClass(operands, COSNumber.class)) {
        return;
    }
    COSNumber x1 = (COSNumber) operands.get(0);
    COSNumber y1 = (COSNumber) operands.get(1);
    COSNumber x2 = (COSNumber) operands.get(2);
    COSNumber y2 = (COSNumber) operands.get(3);
    COSNumber x3 = (COSNumber) operands.get(4);
    COSNumber y3 = (COSNumber) operands.get(5);

    Point2D.Float point1 = context.transformedPoint(x1.floatValue(), y1.floatValue());
    Point2D.Float point2 = context.transformedPoint(x2.floatValue(), y2.floatValue());
    Point2D.Float point3 = context.transformedPoint(x3.floatValue(), y3.floatValue());

    linePath.curveTo(point1.x, point1.y, point2.x, point2.y, point3.x, point3.y);
}
 
Example 16
Source Project: jdk8u_jdk   Source File: WWindowPeer.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * For the scaling graphics and a decorated toplevel as the destination,
 * calculates the rounding error of the toplevel insets.
 *
 * @return the left/top insets rounding error, in device space
 */
private Point2D getInsetsRoundingError(SunGraphics2D g) {
    Point2D.Double err = new Point2D.Double(0, 0);
    if (g.transformState >= SunGraphics2D.TRANSFORM_TRANSLATESCALE && !isTargetUndecorated()) {
        Insets sysInsets = getSysInsets();
        if (sysInsets != null) {
            Insets insets = ((Window)target).getInsets();
            // insets.left/top is a scaled down rounded value
            // insets.left/top * tx.scale is a scaled up value (which contributes to graphics translate)
            // sysInsets.left/top is the precise system value
            err.x = sysInsets.left - insets.left * g.transform.getScaleX();
            err.y = sysInsets.top - insets.top * g.transform.getScaleY();
        }
    }
    return err;
}
 
Example 17
private static BufferedImage createTestImage() {
    int w = 1024;
    int h = 768;

    BufferedImage img = new
        BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img.createGraphics();
    Color[] colors = { Color.red, Color.green, Color.blue };
    float[] dist = {0.0f, 0.5f, 1.0f };
    Point2D center = new Point2D.Float(0.5f * w, 0.5f * h);

    RadialGradientPaint p =
        new RadialGradientPaint(center, 0.5f * w, dist, colors);
    g.setPaint(p);
    g.fillRect(0, 0, w, h);
    g.dispose();

    return img;
}
 
Example 18
Source Project: JMapProjLib   Source File: BoggsProjection.java    License: Apache License 2.0 6 votes vote down vote up
public Point2D.Double project(double lplam, double lpphi, Point2D.Double out) {
	double theta, th1, c;
	int i;

	theta = lpphi;
	if (Math.abs(Math.abs(lpphi) - MapMath.HALFPI) < EPS)
		out.x = 0.;
	else {
		c = Math.sin(theta) * Math.PI;
		for (i = NITER; i > 0; --i) {
			theta -= th1 = (theta + Math.sin(theta) - c) /
				(1. + Math.cos(theta));
			if (Math.abs(th1) < EPS) break;
		}
		theta *= 0.5;
		out.x = FXC * lplam / (1. / Math.cos(lpphi) + FXC2 / Math.cos(theta));
	}
	out.y = FYC * (lpphi + FYC2 * Math.sin(theta));
	return out;
}
 
Example 19
Source Project: inception   Source File: PDFExtractor.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3)
{
    float h = getPageHeight();
    addDraw("RECTANGLE", (float) p0.getX(), h - (float) p0.getY(), (float) p1.getX(),
        h - (float) p1.getY(), (float) p2.getX(), h - (float) p2.getY(), (float) p3.getX(),
        h - (float) p3.getY());
}
 
Example 20
@Test
public void testCircleFitting() {
    Circle circle = new Circle();
    circle.addPoint( 30.0,  68.0);
    circle.addPoint( 50.0,  -6.0);
    circle.addPoint(110.0, -20.0);
    circle.addPoint( 35.0,  15.0);
    circle.addPoint( 45.0,  97.0);
    NonLinearConjugateGradientOptimizer underlying =
        new NonLinearConjugateGradientOptimizer(ConjugateGradientFormula.POLAK_RIBIERE);
    JDKRandomGenerator g = new JDKRandomGenerator();
    g.setSeed(753289573253l);
    RandomVectorGenerator generator =
        new UncorrelatedRandomVectorGenerator(new double[] { 50.0, 50.0 }, new double[] { 10.0, 10.0 },
                                              new GaussianRandomGenerator(g));
    MultiStartDifferentiableMultivariateRealOptimizer optimizer =
        new MultiStartDifferentiableMultivariateRealOptimizer(underlying, 10, generator);
    optimizer.setConvergenceChecker(new SimpleScalarValueChecker(1.0e-10, 1.0e-10));
    BrentSolver solver = new BrentSolver();
    RealPointValuePair optimum =
        optimizer.optimize(200, circle, GoalType.MINIMIZE, new double[] { 98.680, 47.345 });
    assertEquals(200, optimizer.getMaxEvaluations());
    RealPointValuePair[] optima = optimizer.getOptima();
    for (RealPointValuePair o : optima) {
        Point2D.Double center = new Point2D.Double(o.getPointRef()[0], o.getPointRef()[1]);
        assertEquals(69.960161753, circle.getRadius(center), 1.0e-8);
        assertEquals(96.075902096, center.x, 1.0e-8);
        assertEquals(48.135167894, center.y, 1.0e-8);
    }
    assertTrue(optimizer.getEvaluations() > 70);
    assertTrue(optimizer.getEvaluations() < 90);
    assertEquals(3.1267527, optimum.getValue(), 1.0e-8);
}
 
Example 21
Source Project: buffer_bci   Source File: ZoomHandlerFX.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Handles a mouse pressed event by recording the initial mouse pointer
 * location.
 * 
 * @param canvas  the JavaFX canvas (<code>null</code> not permitted).
 * @param e  the mouse event (<code>null</code> not permitted).
 */
@Override
public void handleMousePressed(ChartCanvas canvas, MouseEvent e) {
    Point2D pt = new Point2D.Double(e.getX(), e.getY());
    Rectangle2D dataArea = canvas.findDataArea(pt);
    if (dataArea != null) {
        this.startPoint = ShapeUtilities.getPointInRectangle(e.getX(),
                e.getY(), dataArea);
    } else {
        this.startPoint = null;
        canvas.clearLiveHandler();
    }
}
 
Example 22
Source Project: bboxdb   Source File: GeoJsonPolygon.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Change the order of the 2d coordinates
 */
public void invertPolygonCoordinates() {
	final List<Point2D> newPointList = new ArrayList<>();
	
	for(final Point2D point : pointList) {
		newPointList.add(new Point2D.Double(point.getY(), point.getX()));
	}
	
	// Change coordinates
	pointList.clear();
	pointList.addAll(newPointList);
}
 
Example 23
Source Project: testarea-pdfbox2   Source File: PageVerticalAnalyzer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void lineTo(float x, float y) throws IOException {
    if (subPath == null) {
        subPath = new Section(y);
        path.add(subPath);
    } else
        subPath.extendTo(y);
    currentPoint = new Point2D.Float(x, y);
}
 
Example 24
Source Project: astor   Source File: MouseWheelHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Handle the case where a plot implements the {@link Zoomable} interface.
 *
 * @param zoomable  the zoomable plot.
 * @param e  the mouse wheel event.
 */
private void handleZoomable(Zoomable zoomable, MouseWheelEvent e) {
    // don't zoom unless the mouse pointer is in the plot's data area
    ChartRenderingInfo info = this.chartPanel.getChartRenderingInfo();
    PlotRenderingInfo pinfo = info.getPlotInfo();
    Point2D p = this.chartPanel.translateScreenToJava2D(e.getPoint());
    if (!pinfo.getDataArea().contains(p)) {
        return;
    }

    Plot plot = (Plot) zoomable;
    // do not notify while zooming each axis
    boolean notifyState = plot.isNotify();
    plot.setNotify(false);
    int clicks = e.getWheelRotation();
    double zf = 1.0 + this.zoomFactor;
    if (clicks < 0) {
        zf = 1.0 / zf;
    }
    if (chartPanel.isDomainZoomable()) {
        zoomable.zoomDomainAxes(zf, pinfo, p, true);
    }
    if (chartPanel.isRangeZoomable()) {
        zoomable.zoomRangeAxes(zf, pinfo, p, true);
    }
    plot.setNotify(notifyState);  // this generates the change event too
}
 
Example 25
Source Project: astor   Source File: SpiderWebPlot.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Draws the label for one axis.
 *
 * @param g2  the graphics device.
 * @param plotArea  the plot area
 * @param value  the value of the label (ignored).
 * @param cat  the category (zero-based index).
 * @param startAngle  the starting angle.
 * @param extent  the extent of the arc.
 */
protected void drawLabel(Graphics2D g2, Rectangle2D plotArea, double value,
                         int cat, double startAngle, double extent) {
    FontRenderContext frc = g2.getFontRenderContext();

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

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

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

    Composite saveComposite = g2.getComposite();

    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
            1.0f));
    g2.setPaint(getLabelPaint());
    g2.setFont(getLabelFont());
    g2.drawString(label, (float) labelLocation.getX(),
            (float) labelLocation.getY());
    g2.setComposite(saveComposite);
}
 
Example 26
Source Project: jdk8u-jdk   Source File: TextLine.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the union of the visual bounds of all the components.
 * This incorporates the path.  It does not include logical
 * bounds (used by carets).
 */
public Rectangle2D getVisualBounds() {
    Rectangle2D result = null;

    for (int i = 0, n = 0; i < fComponents.length; i++, n += 2) {
        TextLineComponent tlc = fComponents[getComponentLogicalIndex(i)];
        Rectangle2D r = tlc.getVisualBounds();

        Point2D.Float pt = new Point2D.Float(locs[n], locs[n+1]);
        if (lp == null) {
            r.setRect(r.getMinX() + pt.x, r.getMinY() + pt.y,
                      r.getWidth(), r.getHeight());
        } else {
            lp.pathToPoint(pt, false, pt);

            AffineTransform at = tlc.getBaselineTransform();
            if (at != null) {
                AffineTransform tx = AffineTransform.getTranslateInstance
                    (pt.x - at.getTranslateX(), pt.y - at.getTranslateY());
                tx.concatenate(at);
                r = tx.createTransformedShape(r).getBounds2D();
            } else {
                r.setRect(r.getMinX() + pt.x, r.getMinY() + pt.y,
                          r.getWidth(), r.getHeight());
            }
        }

        if (result == null) {
            result = r;
        } else {
            result.add(r);
        }
    }

    if (result == null) {
        result = new Rectangle2D.Float(Float.MAX_VALUE, Float.MAX_VALUE, Float.MIN_VALUE, Float.MIN_VALUE);
    }

    return result;
}
 
Example 27
Source Project: SproutLife   Source File: ImageManager.java    License: MIT License 5 votes vote down vote up
public Rectangle2D.Double getRendererBounds(int imageWidth, int imageHeight,
                                            Point2D.Double centerLocation) {
    double actualWidth = imageWidth / panelController.getBoardRenderer().getZoom();
    double actualHeight = imageHeight / panelController.getBoardRenderer().getZoom();
    return new Rectangle2D.Double(centerLocation.x - actualWidth/2,
                                  centerLocation.y - actualHeight/2,
                                  actualWidth, actualHeight);
}
 
Example 28
Source Project: Pixelitor   Source File: CornerHandle.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void drawWidthDisplay(DragDisplay dd, Dimension2D size) {
    Direction horEdgeDirection = getHorEdgeDirection();
    String widthString = DragDisplay.getWidthDisplayString(size.getWidth());
    Point2D horHalf = getHorHalfPoint();
    float horX = (float) (horHalf.getX() + horEdgeDirection.dx);
    float horY = (float) (horHalf.getY() + horEdgeDirection.dy);
    dd.drawOneLine(widthString, horX, horY);
}
 
Example 29
Source Project: workcraft   Source File: Grid.java    License: MIT License 5 votes vote down vote up
/**
 * Recalculates visible grid lines based on the viewport parameters.
 * @param viewport
 * The viewport to calculate gridlines for.
 */
public void updateGrid(Viewport viewport) {
    Rectangle view = viewport.getShape();
    if (view.isEmpty()) return;

    // Compute the visible user space area from the viewport
    Point2D visibleUL = new Point2D.Double();
    Point2D visibleLR = new Point2D.Double();
    Point viewLL = new Point(view.x, view.height + view.y);
    Point viewUR = new Point(view.width + view.x, view.y);
    viewport.getInverseTransform().transform(viewLL, visibleUL);
    viewport.getInverseTransform().transform(viewUR, visibleLR);

    // Dynamic line interval scaling
    double visibleHeight = visibleUL.getY() - visibleLR.getY();
    if (majorInterval > 0) {
        while (visibleHeight / majorInterval > maxThreshold) {
            majorInterval *= intervalScaleFactor;
        }
        while (visibleHeight / majorInterval < minThreshold) {
            majorInterval /= intervalScaleFactor;
        }
    }

    if (EditorCommonSettings.getLightGrid()) {
        updateGridMinorCrosses(viewport, majorInterval * minorIntervalFactor);
        updateGridMajorCrosses(viewport, majorInterval);
    } else {
        updateGridMinorLines(viewport, majorInterval * minorIntervalFactor);
        updateGridMajorLines(viewport, majorInterval);
    }

    for (GridListener l : listeners) {
        l.gridChanged(this);
    }
}
 
Example 30
Source Project: pumpernickel   Source File: CubicPath.java    License: MIT License 5 votes vote down vote up
public void getNextControl(Point2D dest, double distanceScale) {
	if (distanceScale == 1) {
		dest.setLocation(nextControl);
	} else {
		double dy = nextControl.getY() - y;
		double dx = nextControl.getX() - x;
		double theta = Math.atan2(dy, dx);
		double distance = Math.sqrt(dy * dy + dx * dx);
		dest.setLocation(
				x + distance * distanceScale * Math.cos(theta), y
						+ distance * distanceScale * Math.sin(theta));
	}
}