List of usage examples for java.awt Graphics2D setStroke
public abstract void setStroke(Stroke s);
From source file:au.org.ala.layers.web.UserDataService.java
@RequestMapping(value = WS_USERDATA_WMS, method = RequestMethod.GET) public void getPointsMap( @RequestParam(value = "CQL_FILTER", required = false, defaultValue = "") String cql_filter, @RequestParam(value = "ENV", required = false, defaultValue = "") String env, @RequestParam(value = "BBOX", required = false, defaultValue = "") String bboxString, @RequestParam(value = "WIDTH", required = false, defaultValue = "") String widthString, @RequestParam(value = "HEIGHT", required = false, defaultValue = "") String heightString, HttpServletRequest request, HttpServletResponse response) { RecordsLookup.setUserDataDao(userDataDao); response.setHeader("Cache-Control", "max-age=86400"); //age == 1 day response.setContentType("image/png"); //only png images generated int width = 256, height = 256; try {//from www .j a v a2 s. c om width = Integer.parseInt(widthString); height = Integer.parseInt(heightString); } catch (Exception e) { logger.error("error parsing to int: " + widthString + " or " + heightString, e); } try { env = URLDecoder.decode(env, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error("error decoding env from UTF-8: " + env, e); } int red = 0, green = 0, blue = 0, alpha = 0; String name = "circle"; int size = 4; boolean uncertainty = false; String highlight = null; String colourMode = null; for (String s : env.split(";")) { String[] pair = s.split(":"); if (pair[0].equals("color")) { while (pair[1].length() < 6) { pair[1] = "0" + pair[1]; } red = Integer.parseInt(pair[1].substring(0, 2), 16); green = Integer.parseInt(pair[1].substring(2, 4), 16); blue = Integer.parseInt(pair[1].substring(4), 16); } else if (pair[0].equals("name")) { name = pair[1]; } else if (pair[0].equals("size")) { size = Integer.parseInt(pair[1]); } else if (pair[0].equals("opacity")) { alpha = (int) (255 * Double.parseDouble(pair[1])); // } else if (pair[0].equals("uncertainty")) { // uncertainty = true; } else if (pair[0].equals("sel")) { try { highlight = URLDecoder.decode(s.substring(4), "UTF-8").replace("%3B", ";"); } catch (Exception e) { } } else if (pair[0].equals("colormode")) { colourMode = pair[1]; } } double[] bbox = new double[4]; int i; i = 0; for (String s : bboxString.split(",")) { try { bbox[i] = Double.parseDouble(s); i++; } catch (Exception e) { logger.error("error converting bounding box value to double: " + s, e); } } try { //adjust bbox extents with half pixel width/height double pixelWidth = (bbox[2] - bbox[0]) / width; double pixelHeight = (bbox[3] - bbox[1]) / height; bbox[0] += pixelWidth / 2; bbox[2] -= pixelWidth / 2; bbox[1] += pixelHeight / 2; bbox[3] -= pixelHeight / 2; //offset for points bounding box by size double xoffset = (bbox[2] - bbox[0]) / (double) width * (size + (highlight != null ? HIGHLIGHT_RADIUS * 2 + size * 0.2 : 0) + 5); double yoffset = (bbox[3] - bbox[1]) / (double) height * (size + (highlight != null ? HIGHLIGHT_RADIUS * 2 + size * 0.2 : 0) + 5); //check offset for points bb by maximum uncertainty (?? 30k ??) if (uncertainty) { double xuoffset = 30000; double yuoffset = 30000; if (xoffset < xuoffset) { xoffset = xuoffset; } if (yoffset < yuoffset) { yoffset = yuoffset; } } //adjust offset for pixel height/width xoffset += pixelWidth; yoffset += pixelHeight; double[][] bb = { { SpatialUtils.convertMetersToLng(bbox[0] - xoffset), SpatialUtils.convertMetersToLat(bbox[1] - yoffset) }, { SpatialUtils.convertMetersToLng(bbox[2] + xoffset), SpatialUtils.convertMetersToLat(bbox[3] + yoffset) } }; double[] pbbox = new double[4]; //pixel bounding box pbbox[0] = SpatialUtils.convertLngToPixel(SpatialUtils.convertMetersToLng(bbox[0])); pbbox[1] = SpatialUtils.convertLatToPixel(SpatialUtils.convertMetersToLat(bbox[1])); pbbox[2] = SpatialUtils.convertLngToPixel(SpatialUtils.convertMetersToLng(bbox[2])); pbbox[3] = SpatialUtils.convertLatToPixel(SpatialUtils.convertMetersToLat(bbox[3])); String lsid = null; int p1 = 0; int p2 = cql_filter.indexOf('&', p1 + 1); if (p2 < 0) { p2 = cql_filter.indexOf(';', p1 + 1); } if (p2 < 0) { p2 = cql_filter.length(); } if (p1 >= 0) { lsid = cql_filter.substring(0, p2); } double[] points = null; ArrayList<QueryField> listHighlight = null; QueryField colours = null; double[] pointsBB = null; Facet facet = null; String[] facetFields = null; if (highlight != null && !(colourMode != null && colourMode.equals("grid"))) { facet = Facet.parseFacet(highlight); facetFields = facet.getFields(); listHighlight = new ArrayList<QueryField>(); } int[] idx = null; if (lsid != null) { Object[] data = (Object[]) RecordsLookup.getData(lsid); points = (double[]) data[1]; pointsBB = (double[]) data[4]; idx = (int[]) data[5]; if (points == null || points.length == 0 || pointsBB[0] > bb[1][0] || pointsBB[2] < bb[0][0] || pointsBB[1] > bb[1][1] || pointsBB[3] < bb[0][1]) { setImageBlank(response); return; } ArrayList<QueryField> fields = (ArrayList<QueryField>) data[2]; for (int j = 0; j < fields.size(); j++) { if (facet != null) { for (int k = 0; k < facetFields.length; k++) { if (facetFields[k].equals(fields.get(j).getName())) { listHighlight.add(fields.get(j)); } } } if (colourMode != null) { if (fields.get(j).getName().equals(colourMode)) { synchronized (fields.get(j)) { //need to resize 'colours' facet to the correct length and store as new QueryField for (int k = 0; k < fields.size(); k++) { if (fields.get(k).getName().equals(colourMode + " resized")) { colours = fields.get(k); } } if (colours == null) { colours = fields.get(j); //does it need to be rebuilt to the correct length? int count = colours.getIntData() != null ? colours.getIntData().length : colours.getLongData() != null ? colours.getLongData().length : colours.getFloatData() != null ? colours.getFloatData().length : colours.getDoubleData() != null ? colours.getDoubleData().length : 0; if (count != points.length / 2) { QueryField qf = new QueryField(); qf.setDisplayName(colours.getDisplayName()); qf.setName(colours.getName() + " resized"); for (int k = 0; k < idx.length; k++) { qf.add(colours.getAsString(idx[k])); } qf.store(); fields.add(qf); colours = qf; } } } } } } } /* TODO: make this a copy instead of create */ BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) img.getGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, width, height); g.setColor(new Color(red, green, blue, alpha)); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int x, y; int pointWidth = size * 2 + 1; double width_mult = (width / (pbbox[2] - pbbox[0])); double height_mult = (height / (pbbox[1] - pbbox[3])); if (colourMode != null && colourMode.equals("grid")) { int divs = 16; double grid_width_mult = (width / (pbbox[2] - pbbox[0])) / (256 / divs); double grid_height_mult = (height / (pbbox[1] - pbbox[3])) / (256 / divs); int[][] gridCounts = new int[divs][divs]; for (i = 0; i < points.length; i += 2) { x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * grid_width_mult); y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3]) * grid_height_mult); if (x >= 0 && x < divs && y >= 0 && y < divs) { gridCounts[x][y]++; } } int xstep = 256 / divs; int ystep = 256 / divs; for (x = 0; x < divs; x++) { for (y = 0; y < divs; y++) { int v = gridCounts[x][y]; if (v > 0) { if (v > 500) { v = 500; } int colour = Legend.getLinearColour(v, 0, 500, 0xFFFFFF00, 0xFFFF0000); g.setColor(new Color(colour)); g.fillRect(x * xstep, y * ystep, xstep, ystep); } } } } else { //circle type if (name.equals("circle")) { if (colours == null) { for (i = 0; i < points.length; i += 2) { if (points[i] >= bb[0][0] && points[i] <= bb[1][0] && points[i + 1] >= bb[0][1] && points[i + 1] <= bb[1][1]) { x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * width_mult); y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3]) * height_mult); g.fillOval(x - size, y - size, pointWidth, pointWidth); } } } else { int prevColour = -1; //!= colours[0] g.setColor(new Color(prevColour)); for (i = 0; i < points.length; i += 2) { if (points[i] >= bb[0][0] && points[i] <= bb[1][0] && points[i + 1] >= bb[0][1] && points[i + 1] <= bb[1][1]) { //colours is made the correct length, see above int thisColour = colours.getColour(i / 2); if (thisColour != prevColour) { g.setColor(new Color(thisColour)); prevColour = thisColour; } x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * width_mult); y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3]) * height_mult); g.fillOval(x - size, y - size, pointWidth, pointWidth); } } } } if (highlight != null && facet != null) { g.setStroke(new BasicStroke(2)); g.setColor(new Color(255, 0, 0, 255)); int sz = size + HIGHLIGHT_RADIUS; int w = sz * 2 + 1; for (i = 0; i < points.length; i += 2) { if (points[i] >= bb[0][0] && points[i] <= bb[1][0] && points[i + 1] >= bb[0][1] && points[i + 1] <= bb[1][1]) { if (facet.isValid(listHighlight, idx[i / 2])) { x = (int) ((SpatialUtils.convertLngToPixel(points[i]) - pbbox[0]) * width_mult); y = (int) ((SpatialUtils.convertLatToPixel(points[i + 1]) - pbbox[3]) * height_mult); g.drawOval(x - sz, y - sz, w, w); } } } } } g.dispose(); try { OutputStream os = response.getOutputStream(); ImageIO.write(img, "png", os); os.flush(); os.close(); } catch (IOException e) { logger.error("error in outputting wms/reflect image as png", e); } } catch (Exception e) { logger.error("error generating wms/reflect tile", e); } //logger.debug("[wms tile: " + (System.currentTimeMillis() - start) + "ms]"); }
From source file:edu.dlnu.liuwenpeng.render.XYBarRenderer.java
/** * Draws the visual representation of a single data item. * * @param g2 the graphics device./*from ww w . jav a2 s. c o m*/ * @param state the renderer state. * @param dataArea the area within which the plot is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (!getItemVisible(series, item)) { return; } IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset; double value0; double value1; if (this.useYInterval) { value0 = intervalDataset.getStartYValue(series, item); value1 = intervalDataset.getEndYValue(series, item); } else { value0 = this.base; value1 = intervalDataset.getYValue(series, item); } if (Double.isNaN(value0) || Double.isNaN(value1)) { return; } if (value0 <= value1) { if (!rangeAxis.getRange().intersects(value0, value1)) { return; } } else { if (!rangeAxis.getRange().intersects(value1, value0)) { return; } } double translatedValue0 = rangeAxis.valueToJava2D(value0, dataArea, plot.getRangeAxisEdge()); double translatedValue1 = rangeAxis.valueToJava2D(value1, dataArea, plot.getRangeAxisEdge()); double bottom = Math.min(translatedValue0, translatedValue1); double top = Math.max(translatedValue0, translatedValue1); double startX = intervalDataset.getStartXValue(series, item); if (Double.isNaN(startX)) { return; } double endX = intervalDataset.getEndXValue(series, item); if (Double.isNaN(endX)) { return; } if (startX <= endX) { if (!domainAxis.getRange().intersects(startX, endX)) { return; } } else { if (!domainAxis.getRange().intersects(endX, startX)) { return; } } RectangleEdge location = plot.getDomainAxisEdge(); double translatedStartX1 = domainAxis.valueToJava2D(startX, dataArea, location); double translatedEndX1 = domainAxis.valueToJava2D(endX, dataArea, location); double translatedWidth = Math.max(1, Math.abs(translatedEndX1 - translatedStartX1)); double translatedStartX = translatedStartX1 - translatedWidth / 2; double translatedEndX = translatedEndX1 - translatedWidth / 2; double left = Math.min(translatedStartX, translatedEndX); if (getMargin() > 0.0) { double cut = translatedWidth * getMargin(); translatedWidth = translatedWidth - cut; left = left + cut / 2; } Rectangle2D bar = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { // clip left and right bounds to data area bottom = Math.max(bottom, dataArea.getMinX()); top = Math.min(top, dataArea.getMaxX()); bar = new Rectangle2D.Double(bottom, left, top - bottom, translatedWidth); } else if (orientation == PlotOrientation.VERTICAL) { // clip top and bottom bounds to data area bottom = Math.max(bottom, dataArea.getMinY()); top = Math.min(top, dataArea.getMaxY()); bar = new Rectangle2D.Double(left, bottom, translatedWidth, top - bottom); } Paint itemPaint = getItemPaint(series, item); if (getGradientPaintTransformer() != null && itemPaint instanceof GradientPaint) { GradientPaint gp = (GradientPaint) itemPaint; itemPaint = getGradientPaintTransformer().transform(gp, bar); } g2.setPaint(itemPaint); g2.fill(bar); if (isDrawBarOutline() && Math.abs(translatedEndX - translatedStartX) > 3) { Stroke stroke = getItemOutlineStroke(series, item); Paint paint = getItemOutlinePaint(series, item); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } if (isItemLabelVisible(series, item)) { XYItemLabelGenerator generator = getItemLabelGenerator(series, item); drawItemLabel(g2, dataset, series, item, plot, generator, bar, value1 < 0.0); } // update the crosshair point double x1 = (startX + endX) / 2.0; double y1 = dataset.getYValue(series, item); double transX1 = domainAxis.valueToJava2D(x1, dataArea, location); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, plot.getRangeAxisEdge()); int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, plot.getOrientation()); EntityCollection entities = state.getEntityCollection(); if (entities != null) { addEntity(entities, bar, dataset, series, item, 0.0, 0.0); } }
From source file:edu.dlnu.liuwenpeng.render.NewXYBarRenderer.java
/** * Draws the visual representation of a single data item. * /*from ww w. ja va 2 s . co m*/ * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the plot is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { if (!getItemVisible(series, item)) { return; } IntervalXYDataset intervalDataset = (IntervalXYDataset) dataset; double value0; double value1; if (this.useYInterval) { value0 = intervalDataset.getStartYValue(series, item); value1 = intervalDataset.getEndYValue(series, item); } else { value0 = this.base; value1 = intervalDataset.getYValue(series, item); } if (Double.isNaN(value0) || Double.isNaN(value1)) { return; } if (value0 <= value1) { if (!rangeAxis.getRange().intersects(value0, value1)) { return; } } else { if (!rangeAxis.getRange().intersects(value1, value0)) { return; } } double translatedValue0 = rangeAxis.valueToJava2D(value0, dataArea, plot.getRangeAxisEdge()); double translatedValue1 = rangeAxis.valueToJava2D(value1, dataArea, plot.getRangeAxisEdge()); double bottom = Math.min(translatedValue0, translatedValue1); double top = Math.max(translatedValue0, translatedValue1); double startX = intervalDataset.getStartXValue(series, item); if (Double.isNaN(startX)) { return; } double endX = intervalDataset.getEndXValue(series, item); if (Double.isNaN(endX)) { return; } if (startX <= endX) { if (!domainAxis.getRange().intersects(startX, endX)) { return; } } else { if (!domainAxis.getRange().intersects(endX, startX)) { return; } } RectangleEdge location = plot.getDomainAxisEdge(); double translatedStartX = domainAxis.valueToJava2D(startX, dataArea, location); double translatedEndX = domainAxis.valueToJava2D(endX, dataArea, location); double translatedWidth = Math.max(1, Math.abs(translatedEndX - translatedStartX)); double left = Math.min(translatedStartX, translatedEndX); if (getMargin() > 0.0) { double cut = translatedWidth * getMargin(); translatedWidth = translatedWidth - cut; left = left + cut / 2; } Rectangle2D bar = null; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { // clip left and right bounds to data area bottom = Math.max(bottom, dataArea.getMinX()); top = Math.min(top, dataArea.getMaxX()); bar = new Rectangle2D.Double(bottom, left, top - bottom, translatedWidth); } else if (orientation == PlotOrientation.VERTICAL) { // clip top and bottom bounds to data area bottom = Math.max(bottom, dataArea.getMinY()); top = Math.min(top, dataArea.getMaxY()); bar = new Rectangle2D.Double(left, bottom, translatedWidth, top - bottom); } /* Paint itemPaint = getItemPaint(series, item); if (getGradientPaintTransformer() != null && itemPaint instanceof GradientPaint) { GradientPaint gp = (GradientPaint) itemPaint; itemPaint = getGradientPaintTransformer().transform(gp, bar); } g2.setPaint(itemPaint); */ if (dataset.getYValue(series, item) >= 0) { g2.setPaint(Color.red); } else { g2.setPaint(Color.green); } g2.fill(bar); if (isDrawBarOutline() && Math.abs(translatedEndX - translatedStartX) > 3) { Stroke stroke = getItemOutlineStroke(series, item); Paint paint = getItemOutlinePaint(series, item); if (stroke != null && paint != null) { g2.setStroke(stroke); g2.setPaint(paint); g2.draw(bar); } } if (isItemLabelVisible(series, item)) { XYItemLabelGenerator generator = getItemLabelGenerator(series, item); drawItemLabel(g2, dataset, series, item, plot, generator, bar, value1 < 0.0); } // update the crosshair point double x1 = (startX + endX) / 2.0; double y1 = dataset.getYValue(series, item); double transX1 = domainAxis.valueToJava2D(x1, dataArea, location); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, plot.getRangeAxisEdge()); int domainAxisIndex = plot.getDomainAxisIndex(domainAxis); int rangeAxisIndex = plot.getRangeAxisIndex(rangeAxis); updateCrosshairValues(crosshairState, x1, y1, domainAxisIndex, rangeAxisIndex, transX1, transY1, plot.getOrientation()); EntityCollection entities = state.getEntityCollection(); if (entities != null) { addEntity(entities, bar, dataset, series, item, 0.0, 0.0); } }
From source file:de.laures.cewolf.jfree.ThermometerPlot.java
/** * Draws the plot on a Java 2D graphics device (such as the screen or a printer). * * @param g2 the graphics device.//from w w w.j av a 2 s . c om * @param area the area within which the plot should be drawn. * @param anchor the anchor point (<code>null</code> permitted). * @param parentState the state from the parent plot, if there is one. * @param info collects info about the drawing. */ public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo info) { RoundRectangle2D outerStem = new RoundRectangle2D.Double(); RoundRectangle2D innerStem = new RoundRectangle2D.Double(); RoundRectangle2D mercuryStem = new RoundRectangle2D.Double(); Ellipse2D outerBulb = new Ellipse2D.Double(); Ellipse2D innerBulb = new Ellipse2D.Double(); String temp = null; FontMetrics metrics = null; if (info != null) { info.setPlotArea(area); } // adjust for insets... RectangleInsets insets = getInsets(); insets.trim(area); drawBackground(g2, area); // adjust for padding... Rectangle2D interior = (Rectangle2D) area.clone(); this.padding.trim(interior); int midX = (int) (interior.getX() + (interior.getWidth() / 2)); int midY = (int) (interior.getY() + (interior.getHeight() / 2)); int stemTop = (int) (interior.getMinY() + getBulbRadius()); int stemBottom = (int) (interior.getMaxY() - getBulbDiameter()); Rectangle2D dataArea = new Rectangle2D.Double(midX - getColumnRadius(), stemTop, getColumnRadius(), stemBottom - stemTop); outerBulb.setFrame(midX - getBulbRadius(), stemBottom, getBulbDiameter(), getBulbDiameter()); outerStem.setRoundRect(midX - getColumnRadius(), interior.getMinY(), getColumnDiameter(), stemBottom + getBulbDiameter() - stemTop, getColumnDiameter(), getColumnDiameter()); Area outerThermometer = new Area(outerBulb); Area tempArea = new Area(outerStem); outerThermometer.add(tempArea); innerBulb.setFrame(midX - getBulbRadius() + getGap(), stemBottom + getGap(), getBulbDiameter() - getGap() * 2, getBulbDiameter() - getGap() * 2); innerStem.setRoundRect(midX - getColumnRadius() + getGap(), interior.getMinY() + getGap(), getColumnDiameter() - getGap() * 2, stemBottom + getBulbDiameter() - getGap() * 2 - stemTop, getColumnDiameter() - getGap() * 2, getColumnDiameter() - getGap() * 2); Area innerThermometer = new Area(innerBulb); tempArea = new Area(innerStem); innerThermometer.add(tempArea); if ((this.dataset != null) && (this.dataset.getValue() != null)) { double current = this.dataset.getValue().doubleValue(); double ds = this.rangeAxis.valueToJava2D(current, dataArea, RectangleEdge.LEFT); int i = getColumnDiameter() - getGap() * 2; // already calculated int j = getColumnRadius() - getGap(); // already calculated int l = (i / 2); int k = (int) Math.round(ds); if (k < (getGap() + interior.getMinY())) { k = (int) (getGap() + interior.getMinY()); l = getBulbRadius(); } Area mercury = new Area(innerBulb); if (k < (stemBottom + getBulbRadius())) { mercuryStem.setRoundRect(midX - j, k, i, (stemBottom + getBulbRadius()) - k, l, l); tempArea = new Area(mercuryStem); mercury.add(tempArea); } g2.setPaint(getCurrentPaint()); g2.fill(mercury); // draw range indicators... if (this.subrangeIndicatorsVisible) { g2.setStroke(this.subrangeIndicatorStroke); Range range = this.rangeAxis.getRange(); // draw start of normal range double value = this.subrangeInfo[NORMAL][RANGE_LOW]; if (range.contains(value)) { double x = midX + getColumnRadius() + 2; double y = this.rangeAxis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(x, y, x + 10, y); g2.setPaint(this.subrangePaint[NORMAL]); g2.draw(line); } // draw start of warning range value = this.subrangeInfo[WARNING][RANGE_LOW]; if (range.contains(value)) { double x = midX + getColumnRadius() + 2; double y = this.rangeAxis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(x, y, x + 10, y); g2.setPaint(this.subrangePaint[WARNING]); g2.draw(line); } // draw start of critical range value = this.subrangeInfo[CRITICAL][RANGE_LOW]; if (range.contains(value)) { double x = midX + getColumnRadius() + 2; double y = this.rangeAxis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); Line2D line = new Line2D.Double(x, y, x + 10, y); g2.setPaint(this.subrangePaint[CRITICAL]); g2.draw(line); } } // draw the axis... if ((this.rangeAxis != null) && (this.axisLocation != NONE)) { int drawWidth = AXIS_GAP; Rectangle2D drawArea; double cursor = 0; switch (this.axisLocation) { case RIGHT: cursor = midX + getColumnRadius(); drawArea = new Rectangle2D.Double(cursor, stemTop, drawWidth, (stemBottom - stemTop + 1)); this.rangeAxis.draw(g2, cursor, area, drawArea, RectangleEdge.RIGHT, null); break; case LEFT: default: //cursor = midX - COLUMN_RADIUS - AXIS_GAP; cursor = midX - getColumnRadius(); drawArea = new Rectangle2D.Double(cursor, stemTop, drawWidth, (stemBottom - stemTop + 1)); this.rangeAxis.draw(g2, cursor, area, drawArea, RectangleEdge.LEFT, null); break; } } // draw text value on screen g2.setFont(this.valueFont); g2.setPaint(this.valuePaint); metrics = g2.getFontMetrics(); switch (this.valueLocation) { case RIGHT: g2.drawString(this.valueFormat.format(current), midX + getColumnRadius() + getGap(), midY); break; case LEFT: String valueString = this.valueFormat.format(current); int stringWidth = metrics.stringWidth(valueString); g2.drawString(valueString, midX - getColumnRadius() - getGap() - stringWidth, midY); break; case BULB: temp = this.valueFormat.format(current); i = metrics.stringWidth(temp) / 2; g2.drawString(temp, midX - i, stemBottom + getBulbRadius() + getGap()); break; default: } /***/ } g2.setPaint(this.thermometerPaint); g2.setFont(this.valueFont); // draw units indicator metrics = g2.getFontMetrics(); int tickX1 = midX - getColumnRadius() - getGap() * 2 - metrics.stringWidth(UNITS[this.units]); if (tickX1 > area.getMinX()) { g2.drawString(UNITS[this.units], tickX1, (int) (area.getMinY() + 20)); } // draw thermometer outline g2.setStroke(this.thermometerStroke); g2.draw(outerThermometer); g2.draw(innerThermometer); drawOutline(g2, area); }
From source file:edu.dlnu.liuwenpeng.render.CandlestickRenderer.java
/** * Draws the visual representation of a single data item. * // w w w . j a va 2 s . c o m * @param g2 the graphics device. * @param state the renderer state. * @param dataArea the area within which the plot is being drawn. * @param info collects info about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { boolean horiz; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { horiz = true; } else if (orientation == PlotOrientation.VERTICAL) { horiz = false; } else { return; } // setup for collecting optional entity info... EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } OHLCDataset highLowData = (OHLCDataset) dataset; double x = highLowData.getXValue(series, item); double yHigh = highLowData.getHighValue(series, item); double yLow = highLowData.getLowValue(series, item); double yOpen = highLowData.getOpenValue(series, item); double yClose = highLowData.getCloseValue(series, item); RectangleEdge domainEdge = plot.getDomainAxisEdge(); double xx = domainAxis.valueToJava2D(x, dataArea, domainEdge); RectangleEdge edge = plot.getRangeAxisEdge(); double yyHigh = rangeAxis.valueToJava2D(yHigh, dataArea, edge); double yyLow = rangeAxis.valueToJava2D(yLow, dataArea, edge); double yyOpen = rangeAxis.valueToJava2D(yOpen, dataArea, edge); double yyClose = rangeAxis.valueToJava2D(yClose, dataArea, edge); double volumeWidth; double stickWidth; if (this.candleWidth > 0) { // These are deliberately not bounded to minimums/maxCandleWidth to // retain old behaviour. volumeWidth = this.candleWidth; stickWidth = this.candleWidth; } else { double xxWidth = 0; int itemCount; switch (this.autoWidthMethod) { case WIDTHMETHOD_AVERAGE: itemCount = highLowData.getItemCount(series); if (horiz) { xxWidth = dataArea.getHeight() / itemCount; } else { xxWidth = dataArea.getWidth() / itemCount; } break; case WIDTHMETHOD_SMALLEST: // Note: It would be nice to pre-calculate this per series itemCount = highLowData.getItemCount(series); double lastPos = -1; xxWidth = dataArea.getWidth(); for (int i = 0; i < itemCount; i++) { double pos = domainAxis.valueToJava2D(highLowData.getXValue(series, i), dataArea, domainEdge); if (lastPos != -1) { xxWidth = Math.min(xxWidth, Math.abs(pos - lastPos)); } lastPos = pos; } break; case WIDTHMETHOD_INTERVALDATA: IntervalXYDataset intervalXYData = (IntervalXYDataset) dataset; double startPos = domainAxis.valueToJava2D(intervalXYData.getStartXValue(series, item), dataArea, plot.getDomainAxisEdge()); double endPos = domainAxis.valueToJava2D(intervalXYData.getEndXValue(series, item), dataArea, plot.getDomainAxisEdge()); xxWidth = Math.abs(endPos - startPos); break; } xxWidth -= 2 * this.autoWidthGap; xxWidth *= this.autoWidthFactor; xxWidth = Math.min(xxWidth, this.maxCandleWidth); volumeWidth = Math.max(Math.min(1, this.maxCandleWidth), xxWidth); stickWidth = Math.max(Math.min(3, this.maxCandleWidth), xxWidth); } Paint p = getItemPaint(series, item); Paint outlinePaint = null; if (this.useOutlinePaint) { outlinePaint = getItemOutlinePaint(series, item); } Stroke s = getItemStroke(series, item); g2.setStroke(s); if (this.drawVolume) { int volume = (int) highLowData.getVolumeValue(series, item); double volumeHeight = volume / this.maxVolume; double min, max; if (horiz) { min = dataArea.getMinX(); max = dataArea.getMaxX(); } else { min = dataArea.getMinY(); max = dataArea.getMaxY(); } double zzVolume = volumeHeight * (max - min); g2.setPaint(getVolumePaint()); Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f)); if (horiz) { g2.fill(new Rectangle2D.Double(min, xx - volumeWidth / 2, zzVolume, volumeWidth)); } else { g2.fill(new Rectangle2D.Double(xx - volumeWidth / 2, max - zzVolume, volumeWidth, zzVolume)); } g2.setComposite(originalComposite); } if (this.useOutlinePaint) { g2.setPaint(outlinePaint); } else { g2.setPaint(p); } double yyMaxOpenClose = Math.max(yyOpen, yyClose); double yyMinOpenClose = Math.min(yyOpen, yyClose); double maxOpenClose = Math.max(yOpen, yClose); double minOpenClose = Math.min(yOpen, yClose); // draw the upper shadow if (yHigh > maxOpenClose) { if (yClose > yOpen) { g2.setPaint(Color.green); } else { g2.setPaint(Color.red); } if (horiz) { g2.draw(new Line2D.Double(yyHigh, xx, yyMaxOpenClose, xx)); } else { g2.draw(new Line2D.Double(xx, yyHigh, xx, yyMaxOpenClose)); } } // draw the lower shadow if (yLow < minOpenClose) { if (yClose > yOpen) { g2.setPaint(Color.green); } else { g2.setPaint(Color.red); } if (horiz) { g2.draw(new Line2D.Double(yyLow, xx, yyMinOpenClose, xx)); } else { g2.draw(new Line2D.Double(xx, yyLow, xx, yyMinOpenClose)); } } // draw the body Rectangle2D body = null; Rectangle2D hotspot = null; double length = Math.abs(yyHigh - yyLow); double base = Math.min(yyHigh, yyLow); if (horiz) { body = new Rectangle2D.Double(yyMinOpenClose, xx - stickWidth / 2, yyMaxOpenClose - yyMinOpenClose, stickWidth); hotspot = new Rectangle2D.Double(base, xx - stickWidth / 2, length, stickWidth); } else { body = new Rectangle2D.Double(xx - stickWidth / 2, yyMinOpenClose, stickWidth, yyMaxOpenClose - yyMinOpenClose); hotspot = new Rectangle2D.Double(xx - stickWidth / 2, base, stickWidth, length); } if (yClose > yOpen) { if (this.upPaint != null) { g2.setPaint(this.upPaint); } else { g2.setPaint(p); } g2.fill(body); } else { if (this.downPaint != null) { g2.setPaint(this.downPaint); } else { g2.setPaint(p); } g2.fill(body); } if (this.useOutlinePaint) { g2.setPaint(outlinePaint); } else { if (yClose > yOpen) { g2.setPaint(Color.green); } else { g2.setPaint(p); } } g2.draw(body); // add an entity for the item... if (entities != null) { addEntity(entities, hotspot, dataset, series, item, 0.0, 0.0); } }
From source file:org.forester.archaeopteryx.TreePanel.java
final void paintPhylogeny(final Graphics2D g, final boolean to_pdf, final boolean to_graphics_file, final int graphics_file_width, final int graphics_file_height, final int graphics_file_x, final int graphics_file_y) { /* GUILHEM_BEG */ _query_sequence = _control_panel.getSelectedQuerySequence(); /* GUILHEM_END */ // Color the background if (!to_pdf) { final Rectangle r = getVisibleRect(); if (!getOptions().isBackgroundColorGradient() || getOptions().isPrintBlackAndWhite()) { g.setColor(getTreeColorSet().getBackgroundColor()); if (!to_graphics_file) { g.fill(r);/*from w w w . ja v a 2 s . co m*/ } else { if (getOptions().isPrintBlackAndWhite()) { g.setColor(Color.WHITE); } g.fillRect(graphics_file_x, graphics_file_y, graphics_file_width, graphics_file_height); } } else { if (!to_graphics_file) { g.setPaint(new GradientPaint(r.x, r.y, getTreeColorSet().getBackgroundColor(), r.x, r.y + r.height, getTreeColorSet().getBackgroundColorGradientBottom())); g.fill(r); } else { g.setPaint(new GradientPaint(graphics_file_x, graphics_file_y, getTreeColorSet().getBackgroundColor(), graphics_file_x, graphics_file_y + graphics_file_height, getTreeColorSet().getBackgroundColorGradientBottom())); g.fillRect(graphics_file_x, graphics_file_y, graphics_file_width, graphics_file_height); } } g.setStroke(new BasicStroke(1)); } else { g.setStroke(new BasicStroke(getOptions().getPrintLineWidth())); } if ((getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED) && (getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR)) { _external_node_index = 0; // Position starting X of tree if (!_phylogeny.isRooted()) { _phylogeny.getRoot().setXcoord(TreePanel.MOVE); } else if ((_phylogeny.getRoot().getDistanceToParent() > 0.0) && getControlPanel().isDrawPhylogram()) { _phylogeny.getRoot().setXcoord((float) (TreePanel.MOVE + (_phylogeny.getRoot().getDistanceToParent() * getXcorrectionFactor()))); } else { _phylogeny.getRoot().setXcoord(TreePanel.MOVE + getXdistance()); } // Position starting Y of tree _phylogeny.getRoot().setYcoord( (getYdistance() * _phylogeny.getRoot().getNumberOfExternalNodes()) + (TreePanel.MOVE / 2.0f)); final int dynamic_hiding_factor = (int) (getTreeFontSet()._fm_large.getHeight() / (1.5 * getYdistance())); if (getControlPanel().isDynamicallyHideData()) { if (dynamic_hiding_factor > 1) { getControlPanel().setDynamicHidingIsOn(true); } else { getControlPanel().setDynamicHidingIsOn(false); } } final PhylogenyNodeIterator it; for (it = _phylogeny.iteratorPreorder(); it.hasNext();) { paintNodeRectangular(g, it.next(), to_pdf, getControlPanel().isDynamicallyHideData() && (dynamic_hiding_factor > 1), dynamic_hiding_factor, to_graphics_file); } if (getOptions().isShowScale()) { if (!(to_graphics_file || to_pdf)) { paintScale(g, getVisibleRect().x, getVisibleRect().y + getVisibleRect().height, to_pdf, to_graphics_file); } else { paintScale(g, graphics_file_x, graphics_file_y + graphics_file_height, to_pdf, to_graphics_file); } } if (getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf) { paintPhylogenyLite(g); } } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED) { if (getControlPanel().getDynamicallyHideData() != null) { getControlPanel().setDynamicHidingIsOn(false); } final double angle = getStartingAngle(); final boolean radial_labels = getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.RADIAL; _dynamic_hiding_factor = 0; if (getControlPanel().isDynamicallyHideData()) { _dynamic_hiding_factor = (int) ((getTreeFontSet()._fm_large.getHeight() * 1.5 * getPhylogeny().getNumberOfExternalNodes()) / (TWO_PI * 10)); } if (getControlPanel().getDynamicallyHideData() != null) { if (_dynamic_hiding_factor > 1) { getControlPanel().setDynamicHidingIsOn(true); } else { getControlPanel().setDynamicHidingIsOn(false); } } paintUnrooted(_phylogeny.getRoot(), angle, (float) (angle + 2 * Math.PI), radial_labels, g, to_pdf, to_graphics_file); if (getOptions().isShowScale()) { if (!(to_graphics_file || to_pdf)) { paintScale(g, getVisibleRect().x, getVisibleRect().y + getVisibleRect().height, to_pdf, to_graphics_file); } else { paintScale(g, graphics_file_x, graphics_file_y + graphics_file_height, to_pdf, to_graphics_file); } } if (getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf) { g.setColor(getTreeColorSet().getOvColor()); paintUnrootedLite(_phylogeny.getRoot(), angle, angle + 2 * Math.PI, g, (getUrtFactorOv() / (getVisibleRect().width / getOvMaxWidth()))); paintOvRectangle(g); } } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR) { final int radius = (int) ((Math.min(getPreferredSize().getWidth(), getPreferredSize().getHeight()) / 2) - (MOVE + getLongestExtNodeInfo())); final int d = radius + MOVE + getLongestExtNodeInfo(); _dynamic_hiding_factor = 0; if (getControlPanel().isDynamicallyHideData() && (radius > 0)) { _dynamic_hiding_factor = (int) ((getTreeFontSet()._fm_large.getHeight() * 1.5 * getPhylogeny().getNumberOfExternalNodes()) / (TWO_PI * radius)); } if (getControlPanel().getDynamicallyHideData() != null) { if (_dynamic_hiding_factor > 1) { getControlPanel().setDynamicHidingIsOn(true); } else { getControlPanel().setDynamicHidingIsOn(false); } } paintCircular(_phylogeny, getStartingAngle(), d, d, radius > 0 ? radius : 0, g, to_pdf, to_graphics_file); if (getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf) { final int radius_ov = (int) (getOvMaxHeight() < getOvMaxWidth() ? getOvMaxHeight() / 2 : getOvMaxWidth() / 2); double x_scale = 1.0; double y_scale = 1.0; int x_pos = getVisibleRect().x + getOvXPosition(); int y_pos = getVisibleRect().y + getOvYPosition(); if (getWidth() > getHeight()) { x_scale = (double) getHeight() / getWidth(); x_pos = ForesterUtil.roundToInt(x_pos / x_scale); } else { y_scale = (double) getWidth() / getHeight(); y_pos = ForesterUtil.roundToInt(y_pos / y_scale); } _at = g.getTransform(); g.scale(x_scale, y_scale); paintCircularLite(_phylogeny, getStartingAngle(), x_pos + radius_ov, y_pos + radius_ov, (int) (radius_ov - (getLongestExtNodeInfo() / (getVisibleRect().width / getOvRectangle().getWidth()))), g); g.setTransform(_at); paintOvRectangle(g); } } }
From source file:ucar.unidata.idv.ui.ImageGenerator.java
/** * Process the lat/lon labels tag/*from ww w . j av a2 s . c o m*/ * * @param child the XML * @param viewManager the associated view manager * @param image the image to draw on * @param imageProps the image properties * * @return a new image * * @throws Exception on badness */ public BufferedImage doLatLonLabels(Element child, ViewManager viewManager, BufferedImage image, Hashtable imageProps) throws Exception { if (viewManager == null) { throw new IllegalArgumentException("Tag " + TAG_LATLONLABELS + " requires a view"); } if (!(viewManager instanceof MapViewManager)) { throw new IllegalArgumentException("Tag " + TAG_LATLONLABELS + " requires a map view"); } MapViewManager mvm = (MapViewManager) viewManager; NavigatedDisplay display = (NavigatedDisplay) viewManager.getMaster(); DecimalFormat format = new DecimalFormat(applyMacros(child, ATTR_FORMAT, "##0.0")); Color color = applyMacros(child, ATTR_COLOR, Color.red); Color lineColor = applyMacros(child, ATTR_LINECOLOR, color); Color bg = applyMacros(child, ATTR_LABELBACKGROUND, (Color) null); double[] latValues = Misc.parseDoubles(applyMacros(child, ATTR_LAT_VALUES, "")); List<String> latLabels = StringUtil.split(applyMacros(child, ATTR_LAT_LABELS, ""), ",", true, true); double[] lonValues = Misc.parseDoubles(applyMacros(child, ATTR_LON_VALUES, "")); List<String> lonLabels = StringUtil.split(applyMacros(child, ATTR_LON_LABELS, ""), ",", true, true); boolean drawLonLines = applyMacros(child, ATTR_DRAWLONLINES, false); boolean drawLatLines = applyMacros(child, ATTR_DRAWLATLINES, false); boolean showTop = applyMacros(child, ATTR_SHOWTOP, false); boolean showBottom = applyMacros(child, ATTR_SHOWBOTTOM, true); boolean showLeft = applyMacros(child, ATTR_SHOWLEFT, true); boolean showRight = applyMacros(child, ATTR_SHOWRIGHT, false); int width = image.getWidth(null); int height = image.getHeight(null); int centerX = width / 2; int centerY = height / 2; EarthLocation nw, ne, se, sw; //don: this what I added Double north = (Double) imageProps.get(ATTR_NORTH); Double south = (Double) imageProps.get(ATTR_SOUTH); Double east = (Double) imageProps.get(ATTR_EAST); Double west = (Double) imageProps.get(ATTR_WEST); //Assume if we have one we have them all if (north != null) { nw = DisplayControlImpl.makeEarthLocation(north.doubleValue(), west.doubleValue(), 0); ne = DisplayControlImpl.makeEarthLocation(north.doubleValue(), east.doubleValue(), 0); sw = DisplayControlImpl.makeEarthLocation(south.doubleValue(), west.doubleValue(), 0); se = DisplayControlImpl.makeEarthLocation(south.doubleValue(), east.doubleValue(), 0); } else { nw = display.screenToEarthLocation(0, 0); ne = display.screenToEarthLocation(width, 0); se = display.screenToEarthLocation(0, height); sw = display.screenToEarthLocation(width, height); } double widthDegrees = ne.getLongitude().getValue() - nw.getLongitude().getValue(); double heightDegrees = ne.getLatitude().getValue() - se.getLatitude().getValue(); Insets insets = getInsets(child, 0); int delta = 2; int bgPad = 1; image = doMatte(image, child, 0); Graphics2D g = (Graphics2D) image.getGraphics(); g.setFont(getFont(child)); FontMetrics fm = g.getFontMetrics(); int lineOffsetRight = applyMacros(child, ATTR_LINEOFFSET_RIGHT, 0); int lineOffsetLeft = applyMacros(child, ATTR_LINEOFFSET_LEFT, 0); int lineOffsetTop = applyMacros(child, ATTR_LINEOFFSET_TOP, 0); int lineOffsetBottom = applyMacros(child, ATTR_LINEOFFSET_BOTTOM, 0); Stroke lineStroke; if (XmlUtil.hasAttribute(child, ATTR_DASHES)) { lineStroke = new BasicStroke((float) applyMacros(child, ATTR_LINEWIDTH, 1.0), BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, Misc.parseFloats(applyMacros(child, ATTR_DASHES, "8")), 0.0f); } else { lineStroke = new BasicStroke((float) applyMacros(child, ATTR_LINEWIDTH, 1.0)); } g.setStroke(lineStroke); double leftLon = nw.getLongitude().getValue(CommonUnit.degree); double rightLon = ne.getLongitude().getValue(CommonUnit.degree); Range lonRange = new Range(leftLon, rightLon); for (int i = 0; i < lonValues.length; i++) { double lon = GeoUtils.normalizeLongitude(lonRange, lonValues[i]); double percent = (lon - nw.getLongitude().getValue()) / widthDegrees; // if(percent<0 || percent>1) continue; String label; if (i < lonLabels.size()) { label = lonLabels.get(i); } else { label = format.format(lonValues[i]); } Rectangle2D rect = fm.getStringBounds(label, g); int baseX = insets.left + (int) (percent * width); int x = baseX - (int) rect.getWidth() / 2; int topY; if (insets.top == 0) { topY = (int) rect.getHeight() + delta; } else { topY = insets.top - delta; } if (drawLonLines) { g.setColor(lineColor); g.drawLine(baseX, insets.top + lineOffsetTop, baseX, insets.top + height - lineOffsetBottom); } if (showTop) { if (bg != null) { g.setColor(bg); g.fillRect(x - bgPad, topY - (int) rect.getHeight() - bgPad, (int) rect.getWidth() + bgPad * 2, (int) rect.getHeight() + bgPad * 2); } g.setColor(color); g.drawString(label, x, topY); } int bottomY; if (insets.bottom == 0) { bottomY = insets.top + height - delta; } else { bottomY = insets.top + height + (int) rect.getHeight() + delta; } if (showBottom) { if (bg != null) { g.setColor(bg); g.fillRect(x - bgPad, bottomY - (int) rect.getHeight() - bgPad, (int) rect.getWidth() + bgPad * 2, (int) rect.getHeight() + bgPad * 2); } g.setColor(color); g.drawString(label, x, bottomY); } } for (int i = 0; i < latValues.length; i++) { double lat = latValues[i]; double percent = 1.0 - (lat - se.getLatitude().getValue()) / heightDegrees; int baseY = insets.top + (int) (percent * height); // if(percent<0 || percent>1) continue; String label; if (i < latLabels.size()) { label = latLabels.get(i); } else { label = format.format(lat); } Rectangle2D rect = fm.getStringBounds(label, g); int y = baseY + (int) rect.getHeight() / 2; int leftX; if (insets.left == 0) { leftX = 0 + delta; } else { leftX = insets.left - (int) rect.getWidth() - delta; } if (drawLonLines) { g.setColor(lineColor); g.drawLine(insets.left + lineOffsetRight, baseY, insets.left + width - lineOffsetRight, baseY); } if (showLeft) { if (bg != null) { g.setColor(bg); g.fillRect(leftX - bgPad, y - (int) rect.getHeight() - bgPad, (int) rect.getWidth() + bgPad * 2, (int) rect.getHeight() + bgPad * 2); } g.setColor(color); g.drawString(label, leftX, y); } if (insets.right == 0) { leftX = insets.left + width - (int) rect.getWidth() - delta; } else { leftX = insets.left + width + delta; } if (showRight) { if (bg != null) { g.setColor(bg); g.fillRect(leftX - bgPad, y - (int) rect.getHeight() - bgPad, (int) rect.getWidth() + bgPad * 2, (int) rect.getHeight() + bgPad * 2); } g.setColor(color); g.drawString(label, leftX, y); } } return image; }
From source file:coolmap.canvas.datarenderer.renderer.impl.NumberToColor.java
@Override public void renderCellSD(Double v, VNode rowNode, VNode columnNode, Graphics2D g2D, int anchorX, int anchorY, int cellWidth, int cellHeight) { if (v == null || v.isNaN()) { //System.out.println(v); _markNull(v, rowNode, columnNode, g2D, anchorX, anchorY, cellWidth, cellHeight); } else {/* w w w . ja v a 2s . c o m*/ try { int index = (int) ((v - _minValue) / (_maxValue - _minValue) * _gradientColors.length); if (index >= _gradientColors.length) { index = _gradientColors.length - 1; } if (index < 0) { index = 0; } Color c = _gradientColors[index]; //System.out.println(c); g2D.setColor(c); // System.out.println((int) cellWidth + " " + ((int) cellHeight)) ; g2D.fillRect((int) anchorX, (int) anchorY, (int) cellWidth, (int) cellHeight); // System.out.println("WH:" + cellWidth + " " + cellHeight); if (drawSubMap.isSelected()) { //paint the sub heatmap block // System.out.println("draw submap"); if (rowNode == null || columnNode == null || rowNode.isSingleNode() && columnNode.isSingleNode()) { return; } else { //need to determine the number of cMatrices CoolMapObject object = getCoolMapObject(); List<CMatrix> matrices = object.getBaseCMatrices(); Double value; //row and column indices Integer[] rowIndices; Integer[] colIndices; //whether they are group node or node if (rowNode.isGroupNode()) { rowIndices = rowNode.getBaseIndicesFromCOntology( (CMatrix) object.getBaseCMatrices().get(0), COntology.ROW); } else { rowIndices = new Integer[] { ((CMatrix) object.getBaseCMatrices().get(0)) .getIndexOfRowName(rowNode.getName()) }; } if (columnNode.isGroupNode()) { colIndices = columnNode.getBaseIndicesFromCOntology( (CMatrix) object.getBaseCMatrices().get(0), COntology.COLUMN); } else { colIndices = new Integer[] { ((CMatrix) object.getBaseCMatrices().get(0)) .getIndexOfColName(columnNode.getName()) }; } //then determine the width int subMatrixWidth = Math.round(cellWidth * 1.0f / matrices.size()); int subAnchorX = anchorX; int subCellHeight = Math.round(cellHeight * 1.0f / rowIndices.length); int subCellWidth = Math.round(subMatrixWidth * 1.0f / colIndices.length); // System.out.println("CW:" + cellWidth + " " + colIndices.length + " " + subCellWidth); // System.out.println("CH:" + cellHeight + " " + rowIndices.length + " " + subCellHeight); if (subCellHeight < 1) { subCellHeight = 1; } if (subCellWidth < 1) { subCellWidth = 1; } for (CMatrix matrix : matrices) { int rowIndex = 0; for (Integer i : rowIndices) { if (i == null || i < 0) { continue; } int columnIndex = 0; for (Integer j : colIndices) { if (j == null || j < 0) { continue; } try { value = (Double) matrix.getValue(i, j); index = (int) ((value - _minValue) / (_maxValue - _minValue) * _gradientColors.length); if (index >= _gradientColors.length) { index = _gradientColors.length - 1; } if (index < 0) { index = 0; } c = _gradientColors[index]; g2D.setColor(c); int subCellX = Math .round(subMatrixWidth * 1.0f * columnIndex / colIndices.length) + subAnchorX; int subCellY = Math.round(cellHeight * 1.0f * rowIndex / rowIndices.length) + anchorY; // System.out.println("WTF:" + columnIndex + " " + rowIndex + "----" + subCellX + " " + subCellY + " " + subCellWidth + " " + subCellHeight); g2D.fillRect(subCellX, subCellY, subCellWidth, subCellHeight); } catch (Exception e) { //draw it here e.printStackTrace(); } columnIndex++; } //end of column loop rowIndex++; } //end of row loop subAnchorX += subMatrixWidth; } //end of matrix loop g2D.setStroke(UI.stroke1); g2D.setColor(Color.BLACK); g2D.drawRect(anchorX, anchorY, cellWidth, cellHeight); } } } catch (Exception e) { // System.out.println("Null pointer exception:" + v + "," + _minValue + "," + _maxValue + "," + _gradientColors + " " + getName() + "" + this); //e.printStackTrace(); } } }
From source file:de.saring.util.gui.jfreechart.StackedRenderer.java
/** * Draws the visual representation of a single data item. * * @param g2 the graphics device.//from w w w . ja v a 2 s . c om * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color information * etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param item the item index (zero-based). * @param crosshairState information about crosshairs on a plot. * @param pass the pass index. */ @Override public void drawItem(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, int item, CrosshairState crosshairState, int pass) { // setup for collecting optional entity info... Shape entityArea = null; EntityCollection entities = null; if (info != null) { entities = info.getOwner().getEntityCollection(); } TableXYDataset tdataset = (TableXYDataset) dataset; // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(y1)) { y1 = 0.0; } double[] stack1 = getStackValues(tdataset, series, item); // get the previous point and the next point so we can calculate a // "hot spot" for the area (used by the chart entity)... double x0 = dataset.getXValue(series, Math.max(item - 1, 0)); double y0 = dataset.getYValue(series, Math.max(item - 1, 0)); if (Double.isNaN(y0)) { y0 = 0.0; } double[] stack0 = getStackValues(tdataset, series, Math.max(item - 1, 0)); int itemCount = dataset.getItemCount(series); double x2 = dataset.getXValue(series, Math.min(item + 1, itemCount - 1)); double y2 = dataset.getYValue(series, Math.min(item + 1, itemCount - 1)); if (Double.isNaN(y2)) { y2 = 0.0; } double[] stack2 = getStackValues(tdataset, series, Math.min(item + 1, itemCount - 1)); double xleft = (x0 + x1) / 2.0; double xright = (x1 + x2) / 2.0; double[] stackLeft = averageStackValues(stack0, stack1); double[] stackRight = averageStackValues(stack1, stack2); double[] adjStackLeft = adjustedStackValues(stack0, stack1); double[] adjStackRight = adjustedStackValues(stack1, stack2); RectangleEdge edge0 = plot.getDomainAxisEdge(); float transX1 = (float) domainAxis.valueToJava2D(x1, dataArea, edge0); float transXLeft = (float) domainAxis.valueToJava2D(xleft, dataArea, edge0); float transXRight = (float) domainAxis.valueToJava2D(xright, dataArea, edge0); if (this.roundXCoordinates) { transX1 = Math.round(transX1); transXLeft = Math.round(transXLeft); transXRight = Math.round(transXRight); } float transY1; RectangleEdge edge1 = plot.getRangeAxisEdge(); GeneralPath left = new GeneralPath(); GeneralPath right = new GeneralPath(); if (y1 >= 0.0) { // handle positive value transY1 = (float) rangeAxis.valueToJava2D(y1 + stack1[1], dataArea, edge1); float transStack1 = (float) rangeAxis.valueToJava2D(stack1[1], dataArea, edge1); float transStackLeft = (float) rangeAxis.valueToJava2D(stackLeft[1], dataArea, edge1); // other than StackedXYAreaRenderer2! // LEFT POLYGON if (y0 >= 0.0) { double yleft = (y0 + y1) / 2.0 + stackLeft[1]; float transYLeft = (float) rangeAxis.valueToJava2D(yleft, dataArea, edge1); left.moveTo(transX1, transY1); left.lineTo(transX1, transStack1); left.lineTo(transXLeft, transStackLeft); left.lineTo(transXLeft, transYLeft); left.closePath(); } else { left.moveTo(transX1, transStack1); left.lineTo(transX1, transY1); left.lineTo(transXLeft, transStackLeft); left.closePath(); } float transStackRight = (float) rangeAxis.valueToJava2D(stackRight[1], dataArea, edge1); // other than StackedXYAreaRenderer2! // RIGHT POLYGON if (y2 >= 0.0) { double yright = (y1 + y2) / 2.0 + stackRight[1]; float transYRight = (float) rangeAxis.valueToJava2D(yright, dataArea, edge1); right.moveTo(transX1, transStack1); right.lineTo(transX1, transY1); right.lineTo(transXRight, transYRight); right.lineTo(transXRight, transStackRight); right.closePath(); } else { right.moveTo(transX1, transStack1); right.lineTo(transX1, transY1); right.lineTo(transXRight, transStackRight); right.closePath(); } } else { // handle negative value transY1 = (float) rangeAxis.valueToJava2D(y1 + stack1[0], dataArea, edge1); float transStack1 = (float) rangeAxis.valueToJava2D(stack1[0], dataArea, edge1); float transStackLeft = (float) rangeAxis.valueToJava2D(adjStackLeft[0], dataArea, edge1); // LEFT POLYGON if (y0 >= 0.0) { left.moveTo(transX1, transStack1); left.lineTo(transX1, transY1); left.lineTo(transXLeft, transStackLeft); left.clone(); } else { double yleft = (y0 + y1) / 2.0 + stackLeft[0]; float transYLeft = (float) rangeAxis.valueToJava2D(yleft, dataArea, edge1); left.moveTo(transX1, transY1); left.lineTo(transX1, transStack1); left.lineTo(transXLeft, transStackLeft); left.lineTo(transXLeft, transYLeft); left.closePath(); } float transStackRight = (float) rangeAxis.valueToJava2D(adjStackRight[0], dataArea, edge1); // RIGHT POLYGON if (y2 >= 0.0) { right.moveTo(transX1, transStack1); right.lineTo(transX1, transY1); right.lineTo(transXRight, transStackRight); right.closePath(); } else { double yright = (y1 + y2) / 2.0 + stackRight[0]; float transYRight = (float) rangeAxis.valueToJava2D(yright, dataArea, edge1); right.moveTo(transX1, transStack1); right.lineTo(transX1, transY1); right.lineTo(transXRight, transYRight); right.lineTo(transXRight, transStackRight); right.closePath(); } } // Get series Paint and Stroke Paint itemPaint = getItemPaint(series, item); if (pass == 0) { g2.setPaint(itemPaint); g2.fill(left); g2.fill(right); } else if (pass == 1) { if (item == 0 || (y1 == 0.0 && y0 == 0.0)) { return; } // get the data point... if (Double.isNaN(y1) || Double.isNaN(x1)) { return; } if (Double.isNaN(y0) || Double.isNaN(x0)) { return; } RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation); double transY0 = rangeAxis.valueToJava2D(y0 + stack0[1], dataArea, yAxisLocation); // only draw if we have good values if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1) || Double.isNaN(transY1)) { return; } state.workingLine.setLine(transX0, transY0, transX1, transY1); if (state.workingLine.intersects(dataArea)) { g2.setStroke(getItemStroke(series, item)); g2.setPaint(super.lookupSeriesPaint(series)); g2.draw(state.workingLine); } return; } // add an entity for the item... if (entities != null) { GeneralPath gp = new GeneralPath(left); gp.append(right, false); entityArea = gp; addEntity(entities, entityArea, dataset, series, item, transX1, transY1); } }
From source file:aprofplot.jfreechart.SamplingXYLineAndShapeRenderer.java
/** * Draws the visual representation of a series as lines. * * @param g2 the graphics device./* w ww . ja v a 2s . co m*/ * @param state the renderer state. * @param dataArea the area within which the data is being drawn. * @param info collects information about the drawing. * @param plot the plot (can be used to obtain standard color * information etc). * @param domainAxis the domain axis. * @param rangeAxis the range axis. * @param dataset the dataset. * @param series the series index (zero-based). * @param crosshairState crosshair information for the plot * (<code>null</code> permitted). * @param pass the pass index. */ protected void drawVerticalSeriesLine(Graphics2D g2, XYItemRendererState state, Rectangle2D dataArea, PlotRenderingInfo info, XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, XYDataset dataset, int series, CrosshairState crosshairState, int pass) { State s = (State) state; RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double lowestVisibleX = domainAxis.getLowerBound(); double highestVisibleX = domainAxis.getUpperBound(); double width = dataArea.getWidth(); double dX = (highestVisibleX - lowestVisibleX) / width * lineWidth; double lowestVisibleY = rangeAxis.getLowerBound(); double highestVisibleY = rangeAxis.getUpperBound(); double lastX = Double.NEGATIVE_INFINITY; double lastY = 0.0; double highY = 0.0; double lowY = 0.0; double openY = 0.0; double closeY = 0.0; boolean lastIntervalDone = false; boolean currentPointVisible = false; boolean lastPointVisible = false; boolean lastPointGood = false; boolean lastPointInInterval = false; boolean pathStarted = false; for (int itemIndex = state.getFirstItemIndex(); itemIndex <= state.getLastItemIndex(); itemIndex++) { double x = dataset.getXValue(series, itemIndex); double y = dataset.getYValue(series, itemIndex); if (!Double.isNaN(x) && !Double.isNaN(y)) { //System.out.println ("Breakpoint 736: pathStarted " + pathStarted); if (!pathStarted) { float startX = (float) domainAxis.valueToJava2D(x, dataArea, xAxisLocation); float startY = (float) rangeAxis.valueToJava2D(y, dataArea, yAxisLocation); s.seriesPath.moveTo(startX, startY); pathStarted = true; } if ((Math.abs(x - lastX) > dX)) { //System.out.println ("Breakpoint 744: leaving interval "); //in any case, add the interval that we are about to leave to the intervalPath float intervalPathX = 0.0f; float intervalPathStartY = 0.0f; float intervalPathEndY = 0.0f; float seriesPathCurrentX = 0.0f; float seriesPathCurrentY = 0.0f; float seriesPathLastX = 0.0f; float seriesPathLastY = 0.0f; //first set some variables intervalPathX = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation); intervalPathStartY = (float) rangeAxis.valueToJava2D(lowY, dataArea, yAxisLocation); intervalPathEndY = (float) rangeAxis.valueToJava2D(highY, dataArea, yAxisLocation); seriesPathCurrentX = (float) domainAxis.valueToJava2D(x, dataArea, xAxisLocation); seriesPathLastX = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation); seriesPathCurrentY = (float) rangeAxis.valueToJava2D(y, dataArea, yAxisLocation); seriesPathLastY = (float) rangeAxis.valueToJava2D(closeY, dataArea, yAxisLocation); /*if((lowY - highY) < 1){ lastPointInInterval = false; }*/ //Double[] values = new Double[]{new Double(openY), new Double(closeY), new Double(highY), new Double(lowY), new Double(lastX)}; /*MessageFormat mf = new MessageFormat("openY {0,number, integer}," + " closeY {1,number, integer}" + " highY {2,number, integer}" + " lowY {3,number, integer}" + "lastX {4,number, integer}");*/ //String text = mf.format(values); //System.out.println("Breakpoint 772" + text); boolean drawInterval = false; if (openY >= closeY) { if (highY > openY || lowY < closeY) { drawInterval = true; } } if (openY < closeY) { if (lowY < openY || highY > closeY) { drawInterval = true; } } //System.out.println("Breakpoint 784, drawInterval " + drawInterval); if (drawInterval) { s.intervalPath.moveTo(intervalPathX, intervalPathStartY); s.intervalPath.lineTo(intervalPathX, intervalPathEndY); } lastIntervalDone = true; //now the series path currentPointVisible = ((x >= lowestVisibleX) && (x <= highestVisibleX) && (y >= lowestVisibleY) && (y <= highestVisibleY)); if (!lastPointGood && !lastPointInInterval) {//last point not valid -- if (currentPointVisible) {//--> if the current position is visible move seriesPath cursor to the current position s.seriesPath.moveTo(seriesPathCurrentX, seriesPathCurrentY); } } else {//last point valid //if the last point was visible and not part of an interval, //we have already moved the seriesPath cursor to the last point, either with or without drawingh a line //thus we only need to draw a line to the current position if (lastPointInInterval && lastPointGood) { s.seriesPath.lineTo(seriesPathLastX, seriesPathLastY); s.seriesPath.lineTo(seriesPathCurrentX, seriesPathCurrentY); } //if the last point was not visible or part of an interval, we have just stored the y values of the last point //and not yet moved the seriesPath cursor. Thus, we need to move the cursor to the last point without drawing //and draw a line to the current position. else { s.seriesPath.lineTo(seriesPathCurrentX, seriesPathCurrentY); } } lastPointVisible = currentPointVisible; lastX = x; lastY = y; highY = y; lowY = y; openY = y; closeY = y; lastPointInInterval = false; } else { lastIntervalDone = false; lastPointInInterval = true; highY = Math.max(highY, y); lowY = Math.min(lowY, y); closeY = y; } lastPointGood = true; } else { lastPointGood = false; } } // if this is the last item, draw the path ... // draw path, but first check whether we need to complete an interval if (!lastIntervalDone) { if (lowY < highY) { float intervalX = (float) domainAxis.valueToJava2D(lastX, dataArea, xAxisLocation); float intervalStartY = (float) rangeAxis.valueToJava2D(lowY, dataArea, yAxisLocation); float intervalEndY = (float) rangeAxis.valueToJava2D(highY, dataArea, yAxisLocation); s.intervalPath.moveTo(intervalX, intervalStartY); s.intervalPath.lineTo(intervalX, intervalEndY); } } PathIterator pi = s.seriesPath.getPathIterator(null); g2.setStroke(getItemStroke(series, 0)); g2.setPaint(getItemPaint(series, 0)); g2.draw(s.seriesPath); g2.draw(s.intervalPath); }