Java Code Examples for java.awt.geom.Rectangle2D.getWidth()

The following are Jave code examples for showing how to use getWidth() of the java.awt.geom.Rectangle2D class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ramus   File: DFDSMovingLabel.java   View Source Code Vote up 6 votes
@Override
public void resetBounds() {
    final FRectangle old = getBounds();
    final Rectangle2D r = getResetsBounds(old);
    double w = r.getWidth();
    double h = r.getHeight();
    if (w < old.getWidth())
        w = old.getWidth();
    if (h < old.getHeight())
        h = old.getHeight();
    setBounds(old.getX()/*-((r.getWidth()-old.getWidth())/2)*/,
            old.getY()/*
                     * -(r.getHeight()-old.getHeight())/2
		 */, w, h);
    // myBounds.setTransformNetBoundsMax(MovingArea.NET_LENGTH);
}
 
Example 2
Project: JavaGraph   File: GraphToEPS.java   View Source Code Vote up 6 votes
@Override
public void renderGraph(JGraph<?> graph, File file) throws PortException {
    // Get graph bounds. If not available, do nothing (probably empty graph)
    Rectangle2D bounds = graph.getGraphBounds();
    if (bounds == null) {
        return;
    }

    try (FileOutputStream fos = new FileOutputStream(file);) {
        EpsGraphics g2d = new EpsGraphics(graph.getModel()
            .getName(), fos, 0, 0, (int) bounds.getWidth(), (int) bounds.getHeight(),
            ColorMode.COLOR_RGB);
        // Render
        toGraphics(graph, g2d);

        // Cleanup
        g2d.close();
    } catch (IOException e) {
        throw new PortException(e);
    }
}
 
Example 3
Project: geomapapp   File: GridDialog.java   View Source Code Vote up 6 votes
void zoomTo() {
	Grid2DOverlay grid = (Grid2DOverlay)gridCB.getSelectedItem();
	if( grid==null ) {
		System.out.println("null");
		return;
	}
	MultiGrid tempMGrid = ((MultiGrid)mGrids.get( grid ));
	XMap m = grid.getMap();
	try {
		Rectangle2D.Double rect = null;
		Rectangle2D shape = (Rectangle2D)tempMGrid.shape.getShapes().get( 0 );
		double w = shape.getWidth();
		double h = shape.getHeight();
		rect = new Rectangle2D.Double( shape.getX()-.25*w, shape.getY()-.25*h, w*1.5, h*1.5 );
		// Tracks zoom before, does zoom, tracks zoom after
		m.setZoomHistoryPast(m);
		m.zoomToRect( rect );
		m.setZoomHistoryNext(m);
		m.repaint();
	} catch(Exception e) {}
}
 
Example 4
Project: pdfbox-graphics2d   File: PdfBoxGraphics2DPaintApplier.java   View Source Code Vote up 6 votes
private void applyTexturePaint(TexturePaint texturePaint) throws IOException {
	Rectangle2D anchorRect = texturePaint.getAnchorRect();
	PDTilingPattern pattern = new PDTilingPattern();
	pattern.setPaintType(PDTilingPattern.PAINT_COLORED);
	pattern.setTilingType(PDTilingPattern.TILING_CONSTANT_SPACING_FASTER_TILING);

	pattern.setBBox(new PDRectangle((float) anchorRect.getX(), (float) anchorRect.getY(),
			(float) anchorRect.getWidth(), (float) anchorRect.getHeight()));
	pattern.setXStep((float) anchorRect.getWidth());
	pattern.setYStep((float) anchorRect.getHeight());

	AffineTransform patternTransform = new AffineTransform();
	patternTransform.translate(0, anchorRect.getHeight());
	patternTransform.scale(1f, -1f);
	pattern.setMatrix(patternTransform);

	PDAppearanceStream appearance = new PDAppearanceStream(document);
	appearance.setResources(pattern.getResources());
	appearance.setBBox(pattern.getBBox());

	PDPageContentStream imageContentStream = new PDPageContentStream(document, appearance,
			((COSStream) pattern.getCOSObject()).createOutputStream());
	BufferedImage texturePaintImage = texturePaint.getImage();
	PDImageXObject imageXObject = imageEncoder.encodeImage(document, imageContentStream, texturePaintImage);

	float ratioW = (float) ((anchorRect.getWidth()) / texturePaintImage.getWidth());
	float ratioH = (float) ((anchorRect.getHeight()) / texturePaintImage.getHeight());
	float paintHeight = (texturePaintImage.getHeight()) * ratioH;
	imageContentStream.drawImage(imageXObject, (float) anchorRect.getX(), (float) (paintHeight + anchorRect.getY()),
			texturePaintImage.getWidth() * ratioW, -paintHeight);
	imageContentStream.close();

	PDColorSpace patternCS1 = new PDPattern(null, imageXObject.getColorSpace());
	COSName tilingPatternName = resources.add(pattern);
	PDColor patternColor = new PDColor(tilingPatternName, patternCS1);

	contentStream.setNonStrokingColor(patternColor);
	contentStream.setStrokingColor(patternColor);
}
 
Example 5
Project: jaer   File: CochleaGenderClassifier.java   View Source Code Vote up 5 votes
public CochleaGenderClassifier (AEChip chip){
    super(chip);
    setNBins(weights.length);
    setMaxIsiUs(9000);
    setMinIsiUs(3000);
    setDirection(Direction.XtimesYDirection);
    titleRenderer = new TextRenderer(new Font("Helvetica",Font.PLAIN,48));
    Rectangle2D bounds = titleRenderer.getBounds(Gender.Unknown.toString());
    titleArea = new Rectangle((int)bounds.getWidth(),(int)bounds.getHeight());
    setPropertyTooltip("Gender params","genderThreshold","threshold for abs(dot product) to classify as (female) speaker. If abs(dot)<genderThreshold then sex is Unknown.");
}
 
Example 6
Project: MapAnalyst   File: ImageWarper.java   View Source Code Vote up 5 votes
/**
     * Warp the source image to create the destination image.
     *
     * @return the new destination image
     */
    public GeoImage warp() {
        Rectangle2D dstBounds = warpedBounds();
        BufferedImage dstImage = createDestinationImage(dstBounds, srcGeoImage.getBufferedImage());
        double cellSize = dstBounds.getWidth() / dstImage.getWidth();
        double destinationWest = dstBounds.getMinX();
        double destinationNorth = dstBounds.getMaxY();
        GeoImage dstGeoImage = new GeoImage(dstImage, destinationWest, destinationNorth, cellSize);
        double[] destXY = new double[2];
        int dstImageWidth = dstImage.getWidth();
        int dstImageHeight = dstImage.getHeight();
        System.out.println("image size: " + dstImageHeight + " " + dstImageWidth);
        for (int row = 0; row < dstImageHeight; row++) {
            for (int col = 0; col < dstImageWidth; col++) {
                destXY[0] = destinationWest + (col + 0.5) * cellSize;
                destXY[1] = destinationNorth - (row + 0.5) * cellSize;
                double[] srcXY = dstToSrcTransformation.transform(destXY);
                interpolation.transform(srcXY, 1);
//                // Convert srcPxX/srcPxY from meters to pixels.
//                int srcPxX = (int) Math.round(srcXY[0]);
//                int srcPxY = (int) Math.round(srcXY[1]);
                
                //if (srcPxX >= 0 && srcPxX < dstImageWidth && srcPxY >= 0 && srcPxY < dstImageHeight) {
                if (srcGeoImage.getBounds2D().contains(srcXY[0], srcXY[1])) {
                    int argb = srcGeoImage.getBilinearInterpol(srcXY[0], srcXY[1]);
                    dstImage.setRGB(col, row, argb);
                }
                // System.out.println(srcPxX + " " + srcPxY);

            }
        }
        return dstGeoImage;
    }
 
Example 7
Project: parabuild-ci   File: SpiderWebPlot.java   View Source Code Vote up 5 votes
/**
 * Returns a cartesian point from a polar angle, length and bounding box
 * 
 * @param bounds  the area inside which the point needs to be.
 * @param angle  the polar angle, in degrees.
 * @param length  the relative length. Given in percent of maximum extend.
 * 
 * @return The cartesian point.
 */
protected Point2D getWebPoint(Rectangle2D bounds, 
                              double angle, double length) {
    
    double angrad = Math.toRadians(angle);
    double x = Math.cos(angrad) * length * bounds.getWidth() / 2;
    double y = -Math.sin(angrad) * length * bounds.getHeight() / 2;

    return new Point2D.Double(bounds.getX() + x + bounds.getWidth() / 2, 
            bounds.getY() + y + bounds.getHeight() / 2);
}
 
Example 8
Project: parabuild-ci   File: WaferMapPlot.java   View Source Code Vote up 5 votes
/**
 * Draws the wafermap view.
 * 
 * @param g2  the graphics device.
 * @param plotArea  the plot area.
 * @param state  the plot state.
 * @param info  the plot rendering info.
 */
public void draw(Graphics2D g2, Rectangle2D plotArea, PlotState state, PlotRenderingInfo info) {

    // if the plot area is too small, just return...
    boolean b1 = (plotArea.getWidth() <= MINIMUM_WIDTH_TO_DRAW);
    boolean b2 = (plotArea.getHeight() <= MINIMUM_HEIGHT_TO_DRAW);
    if (b1 || b2) {
        return;
    }

    // record the plot area...
    if (info != null) {
        info.setPlotArea(plotArea);
    }

    // adjust the drawing area for the plot insets (if any)...
    Insets insets = getInsets();
    if (insets != null) {
        plotArea.setRect(plotArea.getX() + insets.left,
                         plotArea.getY() + insets.top,
                         plotArea.getWidth() - insets.left - insets.right,
                         plotArea.getHeight() - insets.top - insets.bottom);
    }

    drawChipGrid(g2, plotArea);       
    drawWaferEdge(g2, plotArea);
    
}
 
Example 9
Project: OpenJSharp   File: PixelToParallelogramConverter.java   View Source Code Vote up 5 votes
public void draw(SunGraphics2D sg2d, Shape s) {
    if (sg2d.strokeState < SunGraphics2D.STROKE_CUSTOM) {
        BasicStroke bs = ((BasicStroke) sg2d.stroke);
        if (s instanceof Rectangle2D) {
            if (bs.getLineJoin() == BasicStroke.JOIN_MITER &&
                bs.getDashArray() == null)
            {
                Rectangle2D r2d = (Rectangle2D) s;
                double w = r2d.getWidth();
                double h = r2d.getHeight();
                double x = r2d.getX();
                double y = r2d.getY();
                if (w >= 0 && h >= 0) {
                    double lw = bs.getLineWidth();
                    drawRectangle(sg2d, x, y, w, h, lw);
                }
                return;
            }
        } else if (s instanceof Line2D) {
            Line2D l2d = (Line2D) s;
            if (drawGeneralLine(sg2d,
                                l2d.getX1(), l2d.getY1(),
                                l2d.getX2(), l2d.getY2()))
            {
                return;
            }
        }
    }

    outpipe.draw(sg2d, s);
}
 
Example 10
Project: parabuild-ci   File: StackedBarRenderer3D.java   View Source Code Vote up 5 votes
/**
 * Calculates the bar width and stores it in the renderer state.
 * 
 * @param plot  the plot.
 * @param dataArea  the data area.
 * @param rendererIndex  the renderer index.
 * @param state  the renderer state.
 */
protected void calculateBarWidth(CategoryPlot plot, 
                                 Rectangle2D dataArea, 
                                 int rendererIndex,
                                 CategoryItemRendererState state) {

    // calculate the bar width
    CategoryAxis domainAxis = getDomainAxis(plot, rendererIndex);
    CategoryDataset data = plot.getDataset(rendererIndex);
    if (data != null) {
        PlotOrientation orientation = plot.getOrientation();
        double space = 0.0;
        if (orientation == PlotOrientation.HORIZONTAL) {
            space = dataArea.getHeight();
        }
        else if (orientation == PlotOrientation.VERTICAL) {
            space = dataArea.getWidth();
        }
        double maxWidth = space * getMaximumBarWidth();
        int columns = data.getColumnCount();
        double categoryMargin = 0.0;
        if (columns > 1) {
            categoryMargin = domainAxis.getCategoryMargin();
        }

        double used = space * (1 - domainAxis.getLowerMargin() 
                                 - domainAxis.getUpperMargin()
                                 - categoryMargin);
        if (columns > 0) {
            state.setBarWidth(Math.min(used / columns, maxWidth));
        }
        else {
            state.setBarWidth(Math.min(used, maxWidth));
        }
    }

}
 
Example 11
Project: OpenJSharp   File: AquaInternalFrameDockIconUI.java   View Source Code Vote up 5 votes
public void paint(final Graphics g) {
    final int width = getWidth();
    final int height = getHeight();

    final Font font = getFont();
    final FontMetrics metrics = getFontMetrics(font);
    g.setFont(font);

    final String text = getText().trim();
    final int ascent = metrics.getAscent();

    final Rectangle2D stringBounds = metrics.getStringBounds(text, g);
    final int halfway = width / 2;

    final int x = (halfway - (int)stringBounds.getWidth() / 2);

    final Graphics2D g2d = g instanceof Graphics2D ? (Graphics2D)g : null;
    if (g2d != null) {
        g.setColor(UIManager.getColor("DesktopIcon.labelBackground"));
        final Object origAA = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        final int roundHeight = height - ROUND_ADDITIONAL_HEIGHT + 1;
        g.fillRoundRect(0, 0, width, roundHeight, roundHeight, roundHeight);

        final int[] xpts = { halfway, halfway + NUB_HEIGHT, halfway - NUB_HEIGHT };
        final int[] ypts = { height, height - NUB_HEIGHT, height - NUB_HEIGHT };
        g.fillPolygon(xpts, ypts, 3);

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, origAA);
    }

    g.setColor(Color.black);
    SwingUtilities2.drawString(this, g, text, x, 2 + ascent);
    g.setColor(Color.white);
    SwingUtilities2.drawString(this, g, text, x, 1 + ascent);
}
 
Example 12
Project: openjdk-jdk10   File: TexturePaint.java   View Source Code Vote up 5 votes
/**
 * Constructs a {@code TexturePaint} object.
 * @param txtr the {@code BufferedImage} object with the texture
 * used for painting
 * @param anchor the {@code Rectangle2D} in user space used to
 * anchor and replicate the texture
 */
public TexturePaint(BufferedImage txtr,
                    Rectangle2D anchor) {
    this.bufImg = txtr;
    this.tx = anchor.getX();
    this.ty = anchor.getY();
    this.sx = anchor.getWidth() / bufImg.getWidth();
    this.sy = anchor.getHeight() / bufImg.getHeight();
}
 
Example 13
Project: parabuild-ci   File: PiePlot.java   View Source Code Vote up 4 votes
/**
 * Draws the labels for the pie sections.
 * 
 * @param g2  the graphics device.
 * @param keys  the keys.
 * @param totalValue  the total value.
 * @param plotArea  the plot area.
 * @param linkArea  the link area.
 * @param state  the state.
 */
protected void drawLabels(Graphics2D g2, List keys, double totalValue, 
                          Rectangle2D plotArea, Rectangle2D linkArea, 
                          PiePlotState state) {   

    Composite originalComposite = g2.getComposite();
    g2.setComposite(
            AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));

    // classify the keys according to which side the label will appear...
    DefaultKeyedValues leftKeys = new DefaultKeyedValues();
    DefaultKeyedValues rightKeys = new DefaultKeyedValues();
   
    double runningTotal1 = 0.0;
    Iterator iterator1 = keys.iterator();
    while (iterator1.hasNext()) {
        Comparable key = (Comparable) iterator1.next();
        boolean include = true;
        double v = 0.0;
        Number n = this.dataset.getValue(key);
        if (n == null) {
            include = !this.ignoreNullValues;
        }
        else {
            v = n.doubleValue();
            include = this.ignoreZeroValues ? v > 0.0 : v >= 0.0;
        }

        if (include) {
            runningTotal1 = runningTotal1 + v;
            // work out the mid angle (0 - 90 and 270 - 360) = right, 
            // otherwise left
            double mid = this.startAngle + (this.direction.getFactor()
                * ((runningTotal1 - v / 2.0) * 360) / totalValue);
            if (Math.cos(Math.toRadians(mid)) < 0.0) {
                leftKeys.addValue(key, new Double(mid));
            }
            else {
                rightKeys.addValue(key, new Double(mid));
            }
        }
    }
   
    g2.setFont(getLabelFont());
    float maxLabelWidth 
        = (float) (getMaximumLabelWidth() * plotArea.getWidth());
    
    // draw the labels...
    if (this.labelGenerator != null) {
        drawLeftLabels(leftKeys, g2, plotArea, linkArea, maxLabelWidth, 
                state);
        drawRightLabels(rightKeys, g2, plotArea, linkArea, maxLabelWidth, 
                state);
    }
    g2.setComposite(originalComposite);

}
 
Example 14
Project: geomapapp   File: MercatorImageOverlay.java   View Source Code Vote up 4 votes
protected void retrieveImage(Rectangle2D rect) {
	double[] wesn = geoImage.wesn;

	int mapRes = geoImage.maxViewRes;

	double zoom = map.getZoom();
	int res = mapRes;
	while (zoom * res / mapRes > 1.5 && res > 1) {
		res /= 2;
	}
	int scale = mapRes / res;
	double wrap = map.getWrap();

	boolean fullWrap = false;
	if (rect.getWidth() > wrap && wrap != -1) {
		rect = new Rectangle2D.Double(0, rect.getY(), wrap, rect
				.getHeight());
		fullWrap = true;
	}

	int x = (int) Math.floor(scale * rect.getX());
	int y = (int) Math.floor(scale * (rect.getY() - 260.));
	int width = (int) Math.ceil(scale * (rect.getX() + rect.getWidth()))
			- x;
	int height = (int) Math.ceil(scale
			* (rect.getY() - 260. + rect.getHeight()))
			- y;

	System.out.println(x + "\t" + y + "\t" + width + "\t" + height);

	Projection proj = map.getProjection();
	Point2D minLonLat = proj.getRefXY(rect.getX(), rect.getMinY());
	Point2D maxLonLat = proj.getRefXY(rect.getMaxX(), rect.getMaxY());

	Point2D minMapXY = proj.getMapXY(wesn[0], wesn[3]);
	Point2D maxMapXY = proj.getMapXY(wesn[1], wesn[2]);

	System.out.println(wesn[0] + "\t" + wesn[1]);
	System.out.println(minMapXY.getX() * scale + "\t" + maxMapXY.getX() * scale);
	System.out.println(x + "\t" + wrap * scale);

	int sX = (int) (minMapXY.getX() * scale - x);
	int sY = (int) ((minMapXY.getY() - 260) * scale - y);

	int eX = (int) (maxMapXY.getX() * scale - x);
	int eY = (int) ((maxMapXY.getY() - 260) * scale - y);

	while (sX > eX) {
		eX += wrap * scale;
	}
	
	System.out.println(sX + "\t" + sY);
	System.out.println(eX + "\t" + eY);
	
	if (width < 0 || height < 0)
		return;

	BufferedImage mercImage = new BufferedImage(width, height,
			BufferedImage.TYPE_INT_ARGB);
	Graphics2D g = mercImage.createGraphics();
	BufferedImage source = geoImage.getImage();
	g.drawImage(geoImage.getImage(), sX, sY, eX, eY, 0, 0, source.getWidth(), source.getHeight(), null);
	if (fullWrap && eX > width) 
	{
		sX = (int) (sX - wrap * scale);
		eX = (int) (eX - wrap * scale);
		g.drawImage(geoImage.getImage(), sX, sY, eX, eY, 0, 0, source.getWidth(), source.getHeight(), null);
	}

	while (x + width > wrap * scale)
		x -= wrap * scale;

	y += 260 * scale;
	setImage(mercImage, x / (double) scale, y / (double) scale,
			1. / scale);
	setRect(x, y, width, height);
}
 
Example 15
Project: parabuild-ci   File: PiePlot.java   View Source Code Vote up 4 votes
/**
 * Draws the labels for the pie sections.
 * 
 * @param g2  the graphics device.
 * @param keys  the keys.
 * @param totalValue  the total value.
 * @param plotArea  the plot area.
 * @param linkArea  the link area.
 * @param state  the state.
 */
protected void drawLabels(Graphics2D g2, List keys, double totalValue, 
                          Rectangle2D plotArea, Rectangle2D linkArea, PiePlotState state) {   

    Composite originalComposite = g2.getComposite();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));

    // classify the keys according to which side the label will appear...
    DefaultKeyedValues leftKeys = new DefaultKeyedValues();
    DefaultKeyedValues rightKeys = new DefaultKeyedValues();
   
    double runningTotal1 = 0.0;
    Iterator iterator1 = keys.iterator();
    while (iterator1.hasNext()) {
        Comparable key = (Comparable) iterator1.next();
        Number n = this.dataset.getValue(key);
        if (n != null) {
            double v = n.doubleValue();
            if (v > 0.0) {
                runningTotal1 = runningTotal1 + v;
                // work out the mid angle (0 - 90 and 270 - 360) = right, otherwise left
                double mid = this.startAngle + (this.direction.getFactor()
                    * ((runningTotal1 - v / 2.0) * 360) / totalValue);
                if (Math.cos(Math.toRadians(mid)) < 0.0) {
                    leftKeys.addValue(key, new Double(mid));
                }
                else {
                    rightKeys.addValue(key, new Double(mid));
                }
            }
        }
    }
   
    g2.setFont(getLabelFont());
    float maxLabelWidth = (float) (getMaximumLabelWidth() * plotArea.getWidth());
    
    // draw the left labels...
    if (this.labelGenerator != null) {

        drawLeftLabels(leftKeys, g2, plotArea, linkArea, maxLabelWidth, state);
        drawRightLabels(rightKeys, g2, plotArea, linkArea, maxLabelWidth, state);

    }
    g2.setComposite(originalComposite);

}
 
Example 16
Project: parabuild-ci   File: MeterPlot.java   View Source Code Vote up 4 votes
/**
 * Draws an arc.
 *
 * @param g2  the graphics device.
 * @param area  the plot area.
 * @param minValue  the minimum value.
 * @param maxValue  the maximum value.
 * @param paint  the paint.
 * @param outlineType  the outline type.
 */
protected void drawArc(Graphics2D g2, Rectangle2D area, double minValue, double maxValue,
             Paint paint, int outlineType) {

    double startAngle = calculateAngle(maxValue);
    double endAngle = calculateAngle(minValue);
    double extent = endAngle - startAngle;

    double x = area.getX();
    double y = area.getY();
    double w = area.getWidth();
    double h = area.getHeight();
    g2.setPaint(paint);

    if (outlineType > 0) {
        g2.setStroke(new BasicStroke(10.0f));
    }
    else {
        g2.setStroke(new BasicStroke(DEFAULT_BORDER_SIZE));
    }

    int joinType = Arc2D.OPEN;
    if (outlineType > 0) {
        if (this.shape == DialShape.PIE) {
            joinType = Arc2D.PIE;
        }
        else if (this.shape == DialShape.CHORD) {
            if (this.meterAngle > 180) {
                joinType = Arc2D.CHORD;
            }
            else {
                joinType = Arc2D.PIE;
            }
        }
        else if (this.shape == DialShape.CIRCLE) {
            joinType = Arc2D.PIE;
            extent = 360;
        }
        else {
            throw new IllegalStateException(
                "MeterPlot.drawArc(...): dialType not recognised."
            );
        }
    }
    Arc2D.Double arc = new Arc2D.Double(x, y, w, h, startAngle, extent, joinType);
    if (outlineType > 0) {
        g2.fill(arc);
    }
    else {
        g2.draw(arc);
    }

}
 
Example 17
Project: SerenityCE   File: TTFFontRenderer.java   View Source Code Vote up 4 votes
/**
 * Sets up the character data and textures.
 *
 * @param characterData The array of character data that should be filled.
 * @param type          The font type. (Regular, Bold, and Italics)
 */
private CharacterData[] setup(CharacterData[] characterData, int type) {
    // Quickly generates the colors.
    generateColors();

    // Changes the type of the font to the given type.
    Font font = this.font.deriveFont(type);

    // An image just to get font data.
    BufferedImage utilityImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);

    // The graphics of the utility image.
    Graphics2D utilityGraphics = (Graphics2D) utilityImage.getGraphics();

    // Sets the font of the utility image to the font.
    utilityGraphics.setFont(font);

    // The font metrics of the utility image.
    FontMetrics fontMetrics = utilityGraphics.getFontMetrics();

    // Iterates through all the characters in the character set of the font renderer.
    for (int index = 0; index < characterData.length; index++) {
        // The character at the current index.
        char character = (char) index;

        // The width and height of the character according to the font.
        Rectangle2D characterBounds = fontMetrics.getStringBounds(character + "", utilityGraphics);

        // The width of the character texture.
        float width = (float) characterBounds.getWidth() + (2 * MARGIN);

        // The height of the character texture.
        float height = (float) characterBounds.getHeight();

        // The image that the character will be rendered to.
        BufferedImage characterImage = new BufferedImage(MathHelper.ceiling_double_int(width), MathHelper.ceiling_double_int(height), BufferedImage.TYPE_INT_ARGB);

        // The graphics of the character image.
        Graphics2D graphics = (Graphics2D) characterImage.getGraphics();

        // Sets the font to the input font/
        graphics.setFont(font);

        // Sets the color to white with no alpha.
        graphics.setColor(new Color(255, 255, 255, 0));

        // Fills the entire image with the color above, makes it transparent.
        graphics.fillRect(0, 0, characterImage.getWidth(), characterImage.getHeight());

        // Sets the color to white to draw the character.
        graphics.setColor(Color.WHITE);

        // Enables anti-aliasing so the font doesn't have aliasing.
        graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, this.fractionalMetrics ? RenderingHints.VALUE_FRACTIONALMETRICS_ON : RenderingHints.VALUE_FRACTIONALMETRICS_OFF);

        // Draws the character.
        graphics.drawString(character + "", MARGIN, fontMetrics.getAscent());

        // Generates a new texture id.
        int textureId = GlStateManager.generateTexture();

        // Allocates the texture in opengl.
        createTexture(textureId, characterImage);

        // Initiates the character data and stores it in the data array.
        characterData[index] = new CharacterData(character, characterImage.getWidth(), characterImage.getHeight(), textureId);
    }

    // Returns the filled character data array.
    return characterData;
}
 
Example 18
Project: rapidminer   File: LinkAndBrushChartPanel.java   View Source Code Vote up 4 votes
@Override
public void mouseReleased(MouseEvent e) {

	// if we've been panning, we need to reset now that the mouse is
	// released...
	Rectangle2D zoomRectangle = (Rectangle2D) getChartFieldValueByName("zoomRectangle");
	Point2D zoomPoint = (Point2D) getChartFieldValueByName("zoomPoint");
	if (getChartFieldValueByName("panLast") != null) {
		setChartFieldValue((getChartFieldByName("panLast")), null);
		setCursor(Cursor.getDefaultCursor());
	} else if (zoomRectangle != null) {
		boolean hZoom = false;
		boolean vZoom = false;
		if ((PlotOrientation) getChartFieldValueByName("orientation") == PlotOrientation.HORIZONTAL) {
			hZoom = (Boolean) getChartFieldValueByName("rangeZoomable");
			vZoom = (Boolean) getChartFieldValueByName("domainZoomable");
		} else {
			hZoom = (Boolean) getChartFieldValueByName("domainZoomable");
			vZoom = (Boolean) getChartFieldValueByName("rangeZoomable");
		}

		boolean zoomTrigger1 = hZoom
				&& Math.abs(e.getX() - zoomPoint.getX()) >= (Integer) getChartFieldValueByName("zoomTriggerDistance");
		boolean zoomTrigger2 = vZoom
				&& Math.abs(e.getY() - zoomPoint.getY()) >= (Integer) getChartFieldValueByName("zoomTriggerDistance");
		if (zoomTrigger1 || zoomTrigger2) {
			if ((hZoom && (e.getX() < zoomPoint.getX())) || (vZoom && (e.getY() < zoomPoint.getY()))) {
				restoreAutoBounds();
			} else {
				double x, y, w, h;
				Rectangle2D screenDataArea = getScreenDataArea((int) zoomPoint.getX(), (int) zoomPoint.getY());
				double maxX = screenDataArea.getMaxX();
				double maxY = screenDataArea.getMaxY();
				// for mouseReleased event, (horizontalZoom || verticalZoom)
				// will be true, so we can just test for either being false;
				// otherwise both are true
				if (!vZoom) {
					x = zoomPoint.getX();
					y = screenDataArea.getMinY();
					w = Math.min(zoomRectangle.getWidth(), maxX - zoomPoint.getX());
					h = screenDataArea.getHeight();
				} else if (!hZoom) {
					x = screenDataArea.getMinX();
					y = zoomPoint.getY();
					w = screenDataArea.getWidth();
					h = Math.min(zoomRectangle.getHeight(), maxY - zoomPoint.getY());
				} else {
					x = zoomPoint.getX();
					y = zoomPoint.getY();
					w = Math.min(zoomRectangle.getWidth(), maxX - zoomPoint.getX());
					h = Math.min(zoomRectangle.getHeight(), maxY - zoomPoint.getY());
				}
				Rectangle2D zoomArea = new Rectangle2D.Double(x, y, w, h);
				zoom(zoomArea);
			}
			setChartFieldValue(getChartFieldByName("zoomPoint"), null);
			setChartFieldValue(getChartFieldByName("zoomRectangle"), null);
		} else {
			// erase the zoom rectangle
			Graphics2D g2 = (Graphics2D) getGraphics();
			if ((Boolean) getChartFieldValueByName("useBuffer")) {
				repaint();
			} else {
				drawZoomRectangle(g2, true);
			}
			g2.dispose();
			setChartFieldValue(getChartFieldByName("zoomPoint"), null);
			setChartFieldValue(getChartFieldByName("zoomRectangle"), null);
		}

	}

	else if (e.isPopupTrigger()) {
		if (getChartFieldValueByName("popup") != null) {
			displayPopupMenu(e.getX(), e.getY());
		}
	}

}
 
Example 19
Project: parabuild-ci   File: CategoryAxis.java   View Source Code Vote up 4 votes
/**
 * Creates a temporary list of ticks that can be used when drawing the axis.
 *
 * @param g2  the graphics device (used to get font measurements).
 * @param state  the axis state.
 * @param dataArea  the area inside the axes.
 * @param edge  the location of the axis.
 * 
 * @return A list of ticks.
 */
public List refreshTicks(Graphics2D g2, 
                         AxisState state,
                         Rectangle2D dataArea,
                         RectangleEdge edge) {

    List ticks = new java.util.ArrayList();
    
    // sanity check for data area...
    if (dataArea.getHeight() <= 0.0 || dataArea.getWidth() < 0.0) {
        return ticks;
    }

    CategoryPlot plot = (CategoryPlot) getPlot();
    List categories = plot.getCategoriesForAxis(this);
    double max = 0.0;
            
    if (categories != null) {
        CategoryLabelPosition position 
                = this.categoryLabelPositions.getLabelPosition(edge);
        float r = this.maximumCategoryLabelWidthRatio;
        if (r <= 0.0) {
            r = position.getWidthRatio();   
        }
              
        float l = 0.0f;
        if (position.getWidthType() == CategoryLabelWidthType.CATEGORY) {
            l = (float) calculateCategorySize(categories.size(), dataArea, 
                    edge);  
        }
        else {
            if (RectangleEdge.isLeftOrRight(edge)) {
                l = (float) dataArea.getWidth();   
            }
            else {
                l = (float) dataArea.getHeight();   
            }
        }
        int categoryIndex = 0;
        Iterator iterator = categories.iterator();
        while (iterator.hasNext()) {
            Comparable category = (Comparable) iterator.next();
            TextBlock label = createLabel(category, l * r, edge, g2);
            if (edge == RectangleEdge.TOP || edge == RectangleEdge.BOTTOM) {
                max = Math.max(max, calculateTextBlockHeight(label, 
                        position, g2));
            }
            else if (edge == RectangleEdge.LEFT 
                    || edge == RectangleEdge.RIGHT) {
                max = Math.max(max, calculateTextBlockWidth(label, 
                        position, g2));
            }
            Tick tick = new CategoryTick(category, label, 
                    position.getLabelAnchor(), position.getRotationAnchor(), 
                    position.getAngle());
            ticks.add(tick);
            categoryIndex = categoryIndex + 1;
        }
    }
    state.setMax(max);
    return ticks;
    
}
 
Example 20
Project: ramus   File: FRectangle.java   View Source Code Vote up 4 votes
public FRectangle(final Rectangle2D rect) {
    x = rect.getX();
    y = rect.getY();
    width = rect.getWidth();
    height = rect.getHeight();
}