예제 #1
0
  /**
   * Draw labels for picking.
   *
   * @param dc Current draw context.
   * @param pickSupport the PickSupport instance to be used.
   */
  protected void doPick(DrawContext dc, PickSupport pickSupport) {
    GL gl = dc.getGL();

    Angle heading = this.rotation;

    double headingDegrees;
    if (heading != null) headingDegrees = heading.degrees;
    else headingDegrees = 0;

    int x = this.screenPoint.x;
    int y = this.screenPoint.y;

    boolean matrixPushed = false;
    try {
      if (headingDegrees != 0) {
        gl.glPushMatrix();
        matrixPushed = true;

        gl.glTranslated(x, y, 0);
        gl.glRotated(headingDegrees, 0, 0, 1);
        gl.glTranslated(-x, -y, 0);
      }

      for (int i = 0; i < this.lines.length; i++) {
        Rectangle2D bounds = this.lineBounds[i];
        double width = bounds.getWidth();
        double height = bounds.getHeight();

        x = this.screenPoint.x;
        if (this.textAlign.equals(AVKey.CENTER)) x = x - (int) (width / 2.0);
        else if (this.textAlign.equals(AVKey.RIGHT)) x = x - (int) width;
        y -= this.lineHeight;

        Color color = dc.getUniquePickColor();
        int colorCode = color.getRGB();
        PickedObject po = new PickedObject(colorCode, this.getPickedObject(), this.position, false);
        pickSupport.addPickableObject(po);

        // Draw line rectangle
        gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue());

        try {
          gl.glBegin(GL.GL_POLYGON);
          gl.glVertex3d(x, y, 0);
          gl.glVertex3d(x + width - 1, y, 0);
          gl.glVertex3d(x + width - 1, y + height - 1, 0);
          gl.glVertex3d(x, y + height - 1, 0);
          gl.glVertex3d(x, y, 0);
        } finally {
          gl.glEnd();
        }

        y -= this.lineSpacing;
      }
    } finally {
      if (matrixPushed) {
        gl.glPopMatrix();
      }
    }
  }
예제 #2
0
  /**
   * Reimplementación del método mouseReleased de Behavior.
   *
   * @param e MouseEvent
   * @throws BehaviorException Excepción lanzada cuando el Behavior.
   */
  public void mouseReleased(MouseEvent e) throws BehaviorException {
    super.mouseReleased(e);
    dragged = false;
    if (getLayoutControl().getFirstPoint() == null) return;
    Point2D p1;
    Point2D p2;
    Point pScreen = getLayoutControl().getLastPoint();

    AffineTransform at = getLayoutControl().getAT();

    p1 = FLayoutUtilities.toSheetPoint(getLayoutControl().getFirstPoint(), at);
    p2 = FLayoutUtilities.toSheetPoint(pScreen, at);

    if (e.getButton() == MouseEvent.BUTTON1) {
      //	Fijamos el nuevo extent
      Rectangle2D.Double r = new Rectangle2D.Double();
      r.setFrameFromDiagonal(p1, p2);

      Rectangle2D rectPixel = new Rectangle();
      rectPixel.setFrameFromDiagonal(getLayoutControl().getFirstPoint(), pScreen);

      RectangleEvent event = new RectangleEvent(r, e, rectPixel);
      listener.rectangle(event);
    }
  }
예제 #3
0
  /**
   * Compute the bounds of the text, if necessary.
   *
   * @param dc the current DrawContext.
   */
  protected void computeBoundsIfNeeded(DrawContext dc) {
    // Do not compute bounds if they are available. Computing text bounds is expensive, so only do
    // this
    // calculation if necessary.
    if (this.bounds != null) return;

    TextRenderer textRenderer =
        OGLTextRenderer.getOrCreateTextRenderer(dc.getTextRendererCache(), this.getFont());

    int width = 0;
    int maxLineHeight = 0;
    this.lineBounds = new Rectangle2D[this.lines.length];

    for (int i = 0; i < this.lines.length; i++) {
      Rectangle2D lineBounds = textRenderer.getBounds(lines[i]);
      width = (int) Math.max(lineBounds.getWidth(), width);

      double thisLineHeight = Math.abs(lineBounds.getY());
      maxLineHeight = (int) Math.max(thisLineHeight, maxLineHeight);

      this.lineBounds[i] = lineBounds;
    }
    this.lineHeight = maxLineHeight;

    // Compute final height using maxLineHeight and number of lines
    this.bounds =
        new Rectangle(
            this.lines.length,
            maxLineHeight,
            width,
            this.lines.length * maxLineHeight + this.lines.length * this.lineSpacing);
  }
예제 #4
0
  @Override
  public Shape getPointShape(PointData data) {
    Row row = data.row;
    int colLabel = getColumn();
    if (colLabel >= row.size()) {
      return null;
    }

    Comparable<?> labelValue = row.get(colLabel);
    if (labelValue == null) {
      return null;
    }

    Format format = getFormat();
    Font font = getFont();
    String text = format.format(labelValue);
    double alignment = getAlignmentX();
    Shape shape = GraphicsUtils.getOutline(text, font, 0f, alignment);

    double alignX = getAlignmentX();
    double alignY = getAlignmentY();
    Rectangle2D bounds = shape.getBounds2D();
    AffineTransform tx =
        AffineTransform.getTranslateInstance(
            -alignX * bounds.getWidth(), alignY * bounds.getHeight());
    shape = tx.createTransformedShape(shape);

    return shape;
  }
예제 #5
0
 public Rectangle2D getSelectedRect() {
   return new Rectangle2D.Double(
       rect.getX() / scale,
       rect.getY() / scale,
       rect.getWidth() / scale,
       rect.getHeight() / scale);
 }
예제 #6
0
  public GraphicSet importSetFromFile(File inputFile, List<String> warnings)
      throws ImportException {
    Writer out = null;
    try {
      // Get a DOMImplementation
      DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
      // Create an instance of org.w3c.dom.Document
      Document document = domImpl.createDocument(null, "svg", null);
      // Create an instance of the SVG Generator
      final SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
      svgGenerator.setTransform(new AffineTransform());
      // Open input file
      PSInputFile in = new PSInputFile(inputFile.getAbsolutePath());
      Rectangle2D bb = this.getBoundingBox(inputFile);
      svgGenerator.setTransform(AffineTransform.getTranslateInstance(-bb.getX(), -bb.getY()));
      Dimension d = new Dimension((int) bb.getWidth(), (int) bb.getHeight());
      // Create processor and associate to input and output file
      Processor processor = new Processor(svgGenerator, d, false);
      processor.setData(in);

      // Process
      processor.process();
      File tmp = File.createTempFile("temp", "svg");
      tmp.deleteOnExit();
      svgGenerator.stream(new FileWriter(tmp));
      GraphicSet result = new SVGImporter().importSetFromFile(tmp, warnings);
      // Assume the EPS has been created with 72DPI (from Inkscape)
      double px2mm = Util.inch2mm(1d / 72d);
      result.setBasicTransform(AffineTransform.getScaleInstance(px2mm, px2mm));
      return result;
    } catch (Exception ex) {
      Logger.getLogger(EPSImporter.class.getName()).log(Level.SEVERE, null, ex);
      throw new ImportException(ex);
    }
  }
예제 #7
0
 /**
  * Returns the frame surrounding the specified view rectangle.
  *
  * @param view the view rectangle (<code>null</code> not permitted).
  * @return The frame rectangle.
  */
 private Rectangle2D viewToFrame(Rectangle2D view) {
   double width = view.getWidth() / this.viewW;
   double height = view.getHeight() / this.viewH;
   double x = view.getX() - (width * this.viewX);
   double y = view.getY() - (height * this.viewY);
   return new Rectangle2D.Double(x, y, width, height);
 }
예제 #8
0
  /**
   * Constructs an instance of a UTM coordinate transform with the supplied Ellipsoid, zone and
   * hemisphere. The ellipsoid should be the one used as a basis for the UTM coordinates. The zone
   * is the UTM zone which has positions to be converted; hemiflag is a boolean, true if points are
   * northern hemisphere. You can convert points from more than one zone and hemisphere by using the
   * method ConvertUtmToLatLon.
   *
   * <p>The reference coordinate system is RealTupleType.LatitudeLongitudeTuple; the incoming units
   * are assumed to be UTM coords based on the input ellipsoid.
   *
   * <p>Most USGS topographic maps use the 1927 North American Datum (NAD 27); new maps are being
   * slowly revised to NAD 83. To construct Ellipsoids for the first argument, import
   * geotransform.jar, and do new CC_Ellipsoid() for NAD 27 (Clark 1866 ellipsoid), or new
   * RF_Ellipsoid() for NAD 83 (GRS 80 ellipsoid), or new WE_Ellipsoid() for WSG 84. See
   * http://www.ai.sri.com/geotransform/api.html for more details about 239 supported datums.
   *
   * @param ellipsoid the basis for some UTM coordinate system; many choices possible
   * @param zone the UTM zone which has positions to be converted
   * @param bounds Linear2DSet describing the bounds of this MapProjection
   * @param hemiflag a boolean, true if points are in the northern hemisphere
   * @throws VisADException
   */
  public UTMCoordinateSystem(Ellipsoid ellipsoid, int zone, boolean hemiflag, Rectangle2D bounds)
      throws VisADException {

    super(RealTupleType.LatitudeLongitudeTuple, new Unit[] {CommonUnit.meter, CommonUnit.meter});

    if (ellipsoid == null) {
      throw new NullPointerException();
    }

    if ((zone < 1) || (zone > 60)) {
      throw new IllegalArgumentException("UTM zone number not in range 1-60");
    }

    if (bounds != null) {
      startX = bounds.getX();
      startY = bounds.getY();
      width = bounds.getWidth();
      height = bounds.getHeight();
    }

    this.ellipsoid = ellipsoid;
    this.onezone = zone;
    this.onehemiflag = hemiflag;

    // initialize the converters
    Utm_To_Gdc_Converter.Init(ellipsoid);
    Gdc_To_Utm_Converter.Init(ellipsoid);
  }
예제 #9
0
 @Override
 public Rectangle2D getStringBounds(String str, Graphics context) {
   lastStringMeasured = str;
   Rectangle2D bounds = m.getStringBounds(str, context);
   lastStringWidth = (int) bounds.getWidth();
   return bounds;
 }
예제 #10
0
  /**
   * A line wrap algorithm, which splits the given line of text into multiple lines based on the
   * current font size and the available line width
   *
   * @param text
   * @param availableWidth
   * @param graphics
   * @param wrap
   * @return a list of strings, representing the lines
   */
  private List<String> splitIntoLines(
      String text, int availableWidth, Graphics2D graphics, boolean wrap) {

    List<String> lines = new ArrayList<String>();
    if (!wrap) {
      lines.add(text);
      return lines;
    }

    String[] words = text.split(" ");
    String currentLine = "";
    for (int i = 0; i < words.length; i++) {

      String tryLine = (currentLine.equals("")) ? words[i] : (currentLine + " " + words[i]);
      Rectangle2D lineBounds = graphics.getFontMetrics().getStringBounds(tryLine, graphics);
      if (lineBounds.getWidth() > availableWidth) {
        lines.add(currentLine);
        currentLine = words[i];
      } else {
        currentLine = tryLine;
      }
    }
    if (!currentLine.equals("")) {
      lines.add(currentLine);
    }
    return lines;
  }
예제 #11
0
  /**
   * Draws a grid line against the domain axis.
   *
   * @param g2 the graphics device.
   * @param plot the plot.
   * @param dataArea the area for plotting data (not yet adjusted for any 3D effect).
   * @param value the Java2D value at which the grid line should be drawn.
   */
  @Override
  public void drawDomainGridline(
      Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea, double value) {

    Line2D line1 = null;
    Line2D line2 = null;
    PlotOrientation orientation = plot.getOrientation();
    if (orientation == PlotOrientation.HORIZONTAL) {
      double y0 = value;
      double y1 = value - getYOffset();
      double x0 = dataArea.getMinX();
      double x1 = x0 + getXOffset();
      double x2 = dataArea.getMaxX();
      line1 = new Line2D.Double(x0, y0, x1, y1);
      line2 = new Line2D.Double(x1, y1, x2, y1);
    } else if (orientation == PlotOrientation.VERTICAL) {
      double x0 = value;
      double x1 = value + getXOffset();
      double y0 = dataArea.getMaxY();
      double y1 = y0 - getYOffset();
      double y2 = dataArea.getMinY();
      line1 = new Line2D.Double(x0, y0, x1, y1);
      line2 = new Line2D.Double(x1, y1, x1, y2);
    }
    g2.setPaint(plot.getDomainGridlinePaint());
    g2.setStroke(plot.getDomainGridlineStroke());
    g2.draw(line1);
    g2.draw(line2);
  }
 public void paint(Graphics g) {
   Graphics2D g_2d = (Graphics2D) g;
   Ellipse2D ellipse = new Ellipse2D.Double(0, 2, 80, 80);
   Rectangle2D rect = new Rectangle2D.Double(40, 2, 80, 80);
   Area a1 = new Area(ellipse);
   Area a2 = new Area(rect);
   a1.intersect(a2); // "Óë"
   g_2d.fill(a1);
   ellipse.setFrame(130, 2, 80, 80);
   rect.setFrame(170, 2, 80, 80);
   a1 = new Area(ellipse);
   a2 = new Area(rect);
   a1.add(a2); // "»ò"
   g_2d.draw(a1);
   ellipse.setFrame(0, 90, 80, 80);
   rect.setFrame(40, 90, 80, 80);
   a1 = new Area(ellipse);
   a2 = new Area(rect);
   a1.subtract(a2); // "²î"
   g_2d.draw(a1);
   ellipse.setFrame(130, 90, 80, 80);
   rect.setFrame(170, 90, 80, 80);
   a1 = new Area(ellipse);
   a2 = new Area(rect);
   a1.exclusiveOr(a2); // "Òì»ò"
   g_2d.fill(a1);
 }
 /**
  * Updates the position and size of the edit panel relative to the given location.
  *
  * @param loc the location the edit panel should be relative to
  * @param absolute if {@code true} the loc is treated as absolute position on the process
  *     renderer; if {@code false} it is treated as relative to the current process
  */
 private void updateEditPanelPosition(final Rectangle2D loc, final boolean absolute) {
   int panelX = (int) loc.getCenterX() - EDIT_PANEL_WIDTH / 2;
   int panelY = (int) loc.getY() - EDIT_PANEL_HEIGHT - ProcessDrawer.PADDING;
   // if panel would be outside process renderer, fix it
   if (panelX < WorkflowAnnotation.MIN_X) {
     panelX = WorkflowAnnotation.MIN_X;
   }
   if (panelY < 0) {
     panelY = (int) loc.getMaxY() + ProcessDrawer.PADDING;
   }
   // last fallback is cramped to the bottom. If that does not fit either, don't care
   if (panelY + EDIT_PANEL_HEIGHT > view.getSize().getHeight() - ProcessDrawer.PADDING * 2) {
     panelY = (int) loc.getMaxY();
   }
   int index = view.getModel().getProcessIndex(model.getSelected().getProcess());
   if (absolute) {
     editPanel.setBounds(panelX, panelY, EDIT_PANEL_WIDTH, EDIT_PANEL_HEIGHT);
   } else {
     Point absoluteP =
         ProcessDrawUtils.convertToAbsoluteProcessPoint(
             new Point(panelX, panelY), index, rendererModel);
     editPanel.setBounds(
         (int) absoluteP.getX(), (int) absoluteP.getY(), EDIT_PANEL_WIDTH, EDIT_PANEL_HEIGHT);
   }
 }
예제 #14
0
 /**
  * Draws the block within the specified area.
  *
  * @param g2 the graphics device.
  * @param area the area.
  * @param params ignored (<code>null</code> permitted).
  * @return An {@link org.jfree.chart.block.EntityBlockResult} or <code>null</code>.
  */
 public Object draw(Graphics2D g2, Rectangle2D area, Object params) {
   Rectangle2D target = (Rectangle2D) area.clone();
   Rectangle2D hotspot = (Rectangle2D) area.clone();
   StandardEntityCollection sec = null;
   if (params instanceof EntityBlockParams && ((EntityBlockParams) params).getGenerateEntities()) {
     sec = new StandardEntityCollection();
     sec.add(new TitleEntity(hotspot, this));
   }
   target = trimMargin(target);
   if (this.backgroundPaint != null) {
     g2.setPaint(this.backgroundPaint);
     g2.fill(target);
   }
   BlockFrame border = getFrame();
   border.draw(g2, target);
   border.getInsets().trim(target);
   BlockContainer container = this.wrapper;
   if (container == null) {
     container = this.items;
   }
   target = trimPadding(target);
   Object val = container.draw(g2, target, params);
   if (val instanceof BlockResult) {
     EntityCollection ec = ((BlockResult) val).getEntityCollection();
     if (ec != null && sec != null) {
       sec.addAll(ec);
       ((BlockResult) val).setEntityCollection(sec);
     }
   }
   return val;
 }
  /** {@inheritDoc } */
  @Override
  public double[] getResolution(final CoordinateReferenceSystem crs) {
    if (CRS.equalsIgnoreMetadata(objectiveCRS, crs)) {
      return getResolution();
    } else {
      final double[] res = new double[crs.getCoordinateSystem().getDimension()];

      final Envelope env;
      try {
        env = CRS.transform(canvasObjectiveBBox2D, crs);
        final Rectangle2D canvasCRSBounds =
            new Rectangle2D.Double(0, 0, env.getSpan(0), env.getSpan(1));
        res[0] = Math.abs(canvasCRSBounds.getWidth() / canvasDisplaybounds.getWidth());
        res[1] = Math.abs(canvasCRSBounds.getHeight() / canvasDisplaybounds.getHeight());
        for (int i = 2; i < res.length; i++) {
          // other dimension are likely to be the temporal and elevation one.
          // we set a hug resolution to ensure that only one slice of data will be retrived.
          res[i] = Double.MAX_VALUE;
        }
      } catch (TransformException ex) {
        LOGGER.log(Level.WARNING, null, ex);
      } catch (IllegalArgumentException ex) {
        LOGGER.log(Level.WARNING, null, ex);
      } catch (Exception ex) {
        LOGGER.log(Level.WARNING, null, ex);
      }

      return adjustResolutionWithDPI(res);
    }
  }
예제 #16
0
  /**
   * Creates and returns a new graphics object.
   *
   * @param graphicsObjectInfo the graphics object info
   * @return a new graphics object
   */
  public GraphicsObject createGraphic(AFPGraphicsObjectInfo graphicsObjectInfo) {
    // set newly created graphics object in g2d
    GraphicsObject graphicsObj = factory.createGraphicsObject();

    // set data object viewport (i.e. position, rotation, dimension, resolution)
    graphicsObj.setViewport(graphicsObjectInfo);

    AFPGraphics2D g2d = graphicsObjectInfo.getGraphics2D();
    g2d.setGraphicsObject(graphicsObj);

    // set color converter (i.e. an rgb to grayscale converter)
    graphicsObj.setColorConverter(g2d.getPaintingState().getColorConverter());

    // paint to graphics object
    Graphics2DImagePainter painter = graphicsObjectInfo.getPainter();
    Rectangle2D area = graphicsObjectInfo.getArea();
    g2d.scale(1, -1);
    g2d.translate(0, -area.getHeight());

    painter.paint(g2d, area);

    graphicsObj.setComplete(true);

    // return painted graphics object
    return graphicsObj;
  }
예제 #17
0
파일: DButton.java 프로젝트: bo198214/4dbb
  public void paint(Graphics g) {
    Graphics2D gc = (Graphics2D) g;
    // for antialiasing text
    gc.setRenderingHint(
        RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    gc.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    Dimension d = getSize();
    // System.out.println(d.width + "x" + d.height);
    // System.out.println(d.width + "," + d.height);
    int w = d.width - 1;
    int h = d.height - 1;
    float brightness = (float) Settings.brightness.getDouble();
    gc.setColor(Color.black);
    gc.fillRect(0, 0, getWidth(), getHeight());

    gc.setColor(new Color(brightness, brightness, brightness));

    if (mouseInside) gc.drawRoundRect(0, 0, w, h, 8, 8);
    else gc.drawRect(0, 0, w, h);
    FontMetrics fm = gc.getFontMetrics();
    Rectangle2D sb = fm.getStringBounds(text, gc);
    double x = (d.width - sb.getWidth()) / 2;
    double y = (d.height + sb.getHeight()) / 2 - fm.getDescent();
    gc.drawString(text, (int) Math.round(x), (int) Math.round(y));
  }
 /**
  * This method is responsible for computing the resolutions in for the provided grid geometry in
  * the provided crs.
  *
  * <p>It is worth to note that the returned resolution array is of length of 2 and it always is
  * lon, lat for the moment.<br>
  * It might be worth to remove the axes reordering code when we are confident enough with the code
  * to handle the north-up crs.
  *
  * <p>TODO use orthodromic distance?
  *
  * @param envelope the GeneralEnvelope
  * @param dim
  * @param crs
  * @throws DataSourceException
  */
 protected static final double[] getResolution(
     GeneralEnvelope envelope, Rectangle2D dim, CoordinateReferenceSystem crs)
     throws DataSourceException {
   double[] requestedRes = null;
   try {
     if (dim != null && envelope != null && crs != null) {
       // do we need to transform the originalEnvelope?
       final CoordinateReferenceSystem envelopeCrs2D =
           CRS.getHorizontalCRS(envelope.getCoordinateReferenceSystem());
       if (envelopeCrs2D != null && !CRS.equalsIgnoreMetadata(crs, envelopeCrs2D)) {
         CoordinateOperationFactory operationFactory = CRS.getCoordinateOperationFactory(true);
         CoordinateOperation op = operationFactory.createOperation(envelopeCrs2D, crs);
         envelope = CRS.transform(op, envelope);
         envelope.setCoordinateReferenceSystem(crs);
       }
       requestedRes = new double[2];
       requestedRes[0] = envelope.getSpan(0) / dim.getWidth();
       requestedRes[1] = envelope.getSpan(1) / dim.getHeight();
     }
     return requestedRes;
   } catch (TransformException e) {
     throw new DataSourceException("Unable to get resolution", e);
   } catch (FactoryException e) {
     throw new DataSourceException("Unable to get resolution", e);
   }
 }
예제 #19
0
  /**
   * Reserve some space on each axis side because we draw a centered label at each extremity.
   *
   * @param g2 the graphics device.
   * @param plot the plot.
   * @param plotArea the plot area.
   * @param edge the edge.
   * @param space the space already reserved.
   * @return The reserved space.
   */
  public AxisSpace reserveSpace(
      Graphics2D g2, Plot plot, Rectangle2D plotArea, RectangleEdge edge, AxisSpace space) {

    this.internalMarkerCycleBoundTick = null;
    AxisSpace ret = super.reserveSpace(g2, plot, plotArea, edge, space);
    if (this.internalMarkerCycleBoundTick == null) {
      return ret;
    }

    FontMetrics fm = g2.getFontMetrics(getTickLabelFont());
    Rectangle2D r =
        TextUtilities.getTextBounds(this.internalMarkerCycleBoundTick.getText(), g2, fm);

    if (RectangleEdge.isTopOrBottom(edge)) {
      if (isVerticalTickLabels()) {
        space.add(r.getHeight() / 2, RectangleEdge.RIGHT);
      } else {
        space.add(r.getWidth() / 2, RectangleEdge.RIGHT);
      }
    } else if (RectangleEdge.isLeftOrRight(edge)) {
      if (isVerticalTickLabels()) {
        space.add(r.getWidth() / 2, RectangleEdge.TOP);
      } else {
        space.add(r.getHeight() / 2, RectangleEdge.TOP);
      }
    }

    return ret;
  }
예제 #20
0
 /** Set the bounds */
 public void setBounds(Rectangle2D bounds) {
   this._bounds = bounds;
   _boundsX0 = bounds.getX();
   _boundsY0 = bounds.getY();
   _boundsX1 = _boundsX0 + bounds.getWidth();
   _boundsY1 = _boundsY0 + bounds.getHeight();
 }
예제 #21
0
  /**
   * Converts a coordinate from Java 2D space to data space.
   *
   * @param java2DValue the coordinate in Java2D space.
   * @param dataArea the data area.
   * @param edge the edge.
   * @return The data value.
   */
  public double java2DToValue(double java2DValue, Rectangle2D dataArea, RectangleEdge edge) {
    Range range = getRange();

    double vmax = range.getUpperBound();
    double vp = getCycleBound();

    double jmin = 0.0;
    double jmax = 0.0;
    if (RectangleEdge.isTopOrBottom(edge)) {
      jmin = dataArea.getMinX();
      jmax = dataArea.getMaxX();
    } else if (RectangleEdge.isLeftOrRight(edge)) {
      jmin = dataArea.getMaxY();
      jmax = dataArea.getMinY();
    }

    if (isInverted()) {
      double jbreak = jmax - (vmax - vp) * (jmax - jmin) / this.period;
      if (java2DValue >= jbreak) {
        return vp + (jmax - java2DValue) * this.period / (jmax - jmin);
      } else {
        return vp - (java2DValue - jmin) * this.period / (jmax - jmin);
      }
    } else {
      double jbreak = (vmax - vp) * (jmax - jmin) / this.period + jmin;
      if (java2DValue <= jbreak) {
        return vp + (java2DValue - jmin) * this.period / (jmax - jmin);
      } else {
        return vp - (jmax - java2DValue) * this.period / (jmax - jmin);
      }
    }
  }
예제 #22
0
 /**
  * Method that exports the current view to a file using a specified file type.
  *
  * @param component Drawable that will be exported.
  * @param mimeType File format as MIME type string.
  * @param file File to export to.
  * @param documentBounds Document boundary rectangle
  */
 private void export(Drawable component, String mimeType, File file, Rectangle2D documentBounds) {
   FileOutputStream destination;
   try {
     destination = new FileOutputStream(file);
   } catch (FileNotFoundException ex) {
     // TODO Auto-generated catch block
     ex.printStackTrace();
     return;
   }
   DrawableWriter writer = DrawableWriterFactory.getInstance().get(mimeType);
   try {
     writer.write(
         component,
         destination,
         documentBounds.getX(),
         documentBounds.getY(),
         documentBounds.getWidth(),
         documentBounds.getHeight());
   } catch (IOException ex) {
     // TODO Auto-generated catch block
     ex.printStackTrace();
   } finally {
     try {
       destination.close();
     } catch (IOException ex2) {
       // TODO Auto-generated catch block
       ex2.printStackTrace();
     }
   }
 }
예제 #23
0
 public void fitSize() {
   BufferedImage bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
   FontMetrics fm = bi.getGraphics().getFontMetrics(font);
   java.awt.geom.Rectangle2D rect = fm.getStringBounds(text, bi.getGraphics());
   w = rect.getWidth() + font.getSize();
   h = rect.getHeight();
 }
예제 #24
0
파일: WorldView.java 프로젝트: pidigi/apple
 private void drawCenteredString(Graphics2D g2d, String txt) {
   int width = getWidth();
   int height = getHeight();
   Rectangle2D bounds = g2d.getFontMetrics().getStringBounds(txt, g2d);
   g2d.drawString(
       txt, width / 2 - (int) bounds.getCenterX(), height / 2 - (int) bounds.getCenterY());
 }
예제 #25
0
  /**
   * Draws the outline for the plot.
   *
   * @param g2 the graphics device.
   * @param plot the plot.
   * @param dataArea the area inside the axes.
   */
  @Override
  public void drawOutline(Graphics2D g2, CategoryPlot plot, Rectangle2D dataArea) {

    float x0 = (float) dataArea.getX();
    float x1 = x0 + (float) Math.abs(this.xOffset);
    float x3 = (float) dataArea.getMaxX();
    float x2 = x3 - (float) Math.abs(this.xOffset);

    float y0 = (float) dataArea.getMaxY();
    float y1 = y0 - (float) Math.abs(this.yOffset);
    float y3 = (float) dataArea.getMinY();
    float y2 = y3 + (float) Math.abs(this.yOffset);

    GeneralPath clip = new GeneralPath();
    clip.moveTo(x0, y0);
    clip.lineTo(x0, y2);
    clip.lineTo(x1, y3);
    clip.lineTo(x3, y3);
    clip.lineTo(x3, y1);
    clip.lineTo(x2, y0);
    clip.closePath();

    // put an outline around the data area...
    Stroke outlineStroke = plot.getOutlineStroke();
    Paint outlinePaint = plot.getOutlinePaint();
    if ((outlineStroke != null) && (outlinePaint != null)) {
      g2.setStroke(outlineStroke);
      g2.setPaint(outlinePaint);
      g2.draw(clip);
    }
  }
예제 #26
0
 public static void drawCenteredString(Graphics g, String str, int x, int y) {
   FontMetrics metrics = g.getFontMetrics(g.getFont());
   Rectangle2D rect = metrics.getStringBounds(str, g);
   int w = (int) (rect.getWidth());
   int h = (int) (rect.getHeight());
   g.drawString(str, x - w / 2, y + h / 2);
 }
예제 #27
0
 PointsInInfinity(Rectangle2D allocation) {
   x0 = allocation.getX() + BARBELL;
   x1 = allocation.getX() + allocation.getWidth() - BARBELL;
   y0 = allocation.getY() + BARBELL;
   y1 = allocation.getY() + allocation.getHeight() - BARBELL;
   resetMap();
 }
예제 #28
0
파일: Maze.java 프로젝트: WarrenGM/Maze
  @Override
  public void draw(Graphics pane) {
    // Next we draw the method name.
    Graphics2D g = (Graphics2D) pane;
    g.setColor(Color.RED);
    g.setRenderingHint(
        RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    g.setFont(new Font("default", Font.BOLD, 12));
    FontMetrics fm = g.getFontMetrics();
    Rectangle2D rect = fm.getStringBounds(method, g);

    g.setColor(Color.BLACK);
    g.fillRoundRect(
        10,
        component.getHeight() - fm.getAscent() - 5,
        (int) rect.getWidth() + 10,
        (int) rect.getHeight(),
        2,
        2);

    g.setColor(Color.WHITE);
    g.drawString(method, 15, component.getHeight() - 5);

    super.draw(pane);
  }
예제 #29
0
파일: DrawTest.java 프로젝트: FrankLiu/pine
  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D) g;

    // draw a rectangle
    double leftX = 100;
    double topY = 100;
    double width = 200;
    double height = 150;

    Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
    g2.draw(rect);

    // draw a enclosed ellipse
    Ellipse2D ellipse = new Ellipse2D.Double();
    ellipse.setFrame(rect);
    g2.draw(ellipse);

    // draw a diagonal line
    g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height));

    // draw a circle with the same center
    double centerX = rect.getCenterX();
    double centerY = rect.getCenterY();
    double radius = 150;

    Ellipse2D circle = new Ellipse2D.Double();
    circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
    g2.draw(circle);
  }
예제 #30
-1
  private void doShooting() {
    PositionFinder p = new PositionFinder(enemies, this);
    en = p.findNearest();
    if (en == null) return;

    Point2D myPos = new Point2D.Double(getX(), getY());

    if (HoT) {
      /* Perform head on target for gun movement */
      aimingPoint = new Point2D.Double(en.getX(), en.getY());
      double turnGunAmt = (getHeadingRadians() + en.getBearingRadians() - getGunHeadingRadians());
      turnGunAmt = Utils.normalRelativeAngle(turnGunAmt);
      setTurnGunRightRadians(turnGunAmt);
    } else {
      /* Perform circular targeting */
      Rectangle2D battlefield =
          new Rectangle2D.Double(0, 0, getBattleFieldWidth(), getBattleFieldHeight());
      long when = calcTimeToReachEnemy();
      aimingPoint = org.pattern.utils.Utils.getFuturePoint(en, when);
      if (!battlefield.contains(aimingPoint)) {
        HoT = true;
        return;
      }
      double theta =
          Utils.normalAbsoluteAngle(
              Math.atan2(aimingPoint.getX() - getX(), aimingPoint.getY() - getY()));
      setTurnGunRightRadians(Utils.normalRelativeAngle(theta - getGunHeadingRadians()));
    }

    if (getGunHeat() == 0) {
      double firePower = 3.0;
      fire(firePower);
    }
  }