java.awt.Graphics2D Java Examples

The following examples show how to use java.awt.Graphics2D. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XYDifferenceRenderer.java    From opensim-gui with Apache License 2.0 6 votes vote down vote up
/**
 * Draws the visual representation of a single data item.
 *
 * @param g2  the graphics device.
 * @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 (horizontal) axis.
 * @param rangeAxis  the range (vertical) 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 (pass == 0) {
        drawItemPass0(g2, dataArea, info, plot, domainAxis, rangeAxis, 
                dataset, series, item, crosshairState);
    }
    else if (pass == 1) {
        drawItemPass1(g2, dataArea, info, plot, domainAxis, rangeAxis, 
                dataset, series, item, crosshairState);
    }

}
 
Example #2
Source File: 1_CategoryPlot.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Draws the domain markers (if any) for an axis and layer.  This method is 
 * typically called from within the draw() method.
 *
 * @param g2  the graphics device.
 * @param dataArea  the data area.
 * @param index  the renderer index.
 * @param layer  the layer (foreground or background).
 * 
 * @see #drawRangeMarkers(Graphics2D, Rectangle2D, int, Layer)
 */
protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea, 
                                 int index, Layer layer) {
                                             
    CategoryItemRenderer r = getRenderer(index);
    if (r == null) {
        return;
    }
    
    Collection markers = getDomainMarkers(index, layer);
    CategoryAxis axis = getDomainAxisForDataset(index);
    if (markers != null && axis != null) {
        Iterator iterator = markers.iterator();
        while (iterator.hasNext()) {
            CategoryMarker marker = (CategoryMarker) iterator.next();
            r.drawDomainMarker(g2, this, axis, marker, dataArea);
        }
    }
    
}
 
Example #3
Source File: GradientXYBarPainter.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Paints a single bar instance.
 *
 * @param g2  the graphics target.
 * @param renderer  the renderer.
 * @param row  the row index.
 * @param column  the column index.
 * @param bar  the bar
 * @param base  indicates which side of the rectangle is the base of the
 *              bar.
 * @param pegShadow  peg the shadow to the base of the bar?
 */
@Override
public void paintBarShadow(Graphics2D g2, XYBarRenderer renderer, int row,
        int column, RectangularShape bar, RectangleEdge base,
        boolean pegShadow) {

    // handle a special case - if the bar colour has alpha == 0, it is
    // invisible so we shouldn't draw any shadow
    Paint itemPaint = renderer.getItemPaint(row, column);
    if (itemPaint instanceof Color) {
        Color c = (Color) itemPaint;
        if (c.getAlpha() == 0) {
            return;
        }
    }

    RectangularShape shadow = createShadow(bar, renderer.getShadowXOffset(),
            renderer.getShadowYOffset(), base, pegShadow);
    g2.setPaint(Color.gray);
    g2.fill(shadow);

}
 
Example #4
Source File: HiDPIPropertiesWindowsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void testScale(double scaleX, double scaleY) {

        Dialog dialog = new Dialog((Frame) null, true) {

            @Override
            public void paint(Graphics g) {
                super.paint(g);
                AffineTransform tx = ((Graphics2D) g).getTransform();
                dispose();
                if (scaleX != tx.getScaleX() || scaleY != tx.getScaleY()) {
                    throw new RuntimeException(String.format("Wrong scale:"
                            + "[%f, %f] instead of [%f, %f].",
                            tx.getScaleX(), tx.getScaleY(), scaleX, scaleY));
                }
            }
        };
        dialog.setSize(200, 300);
        dialog.setVisible(true);
    }
 
Example #5
Source File: SymbolAxis.java    From opensim-gui with Apache License 2.0 6 votes vote down vote up
/**
 * Draws the grid bands.  Alternate bands are colored using 
 * <CODE>gridBandPaint<CODE> (<CODE>DEFAULT_GRID_BAND_PAINT</CODE> by 
 * default).
 *
 * @param g2  the graphics device.
 * @param plotArea  the area within which the chart should be drawn.
 * @param dataArea  the area within which the plot should be drawn (a 
 *                  subset of the drawArea).
 * @param edge  the axis location.
 * @param ticks  the ticks.
 */
protected void drawGridBands(Graphics2D g2,
                             Rectangle2D plotArea, 
                             Rectangle2D dataArea,
                             RectangleEdge edge, 
                             List ticks) {

    Shape savedClip = g2.getClip();
    g2.clip(dataArea);
    if (RectangleEdge.isTopOrBottom(edge)) {
        drawGridBandsHorizontal(g2, plotArea, dataArea, true, ticks);
    }
    else if (RectangleEdge.isLeftOrRight(edge)) {
        drawGridBandsVertical(g2, plotArea, dataArea, true, ticks);
    }
    g2.setClip(savedClip);

}
 
Example #6
Source File: ColorEditor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Paints the current value. Implements <code>ProepertyEditor</code> interface. */
public void paintValue(Graphics g, Rectangle rectangle) {
    int px;

    ((Graphics2D)g).setRenderingHints (getHints ());
    
    if (this.superColor != null) {
        Color color = g.getColor();
        g.drawRect(rectangle.x, rectangle.y + rectangle.height / 2 - 5 , 10, 10);
        g.setColor(this.superColor);
        g.fillRect(rectangle.x + 1, rectangle.y + rectangle.height / 2 - 4 , 9, 9);
        g.setColor(color);
        px = 18;
    }
    else px = 0;

    FontMetrics fm = g.getFontMetrics();
    g.drawString(getAsText(), rectangle.x + px, rectangle.y +
                  (rectangle.height - fm.getHeight()) / 2 + fm.getAscent());
}
 
Example #7
Source File: ViewRenderer.java    From hprof-tools with MIT License 6 votes vote down vote up
private void renderView(View view, Graphics2D canvas) {
    Drawable background = view.getBackground();
    canvas.translate(view.left, view.top);
    if (renderBackgrounds && background != null) {
        if (forceAlpha) {
            background.setAlpha(120);
        }
        else {
            background.setAlpha(255);
        }
        background.draw(canvas, 0, 0, view.getWidth(), view.getHeight());
    }
    canvas.setColor(getViewOutlineColor(view));
    canvas.setColor(view.isSelected() ? Color.RED : Color.BLACK);
    canvas.setStroke(view.isSelected() ? THICK_LINE : THIN_LINE);
    if (showBounds) {
        canvas.drawRect(0, 0, view.getWidth(), view.getHeight());
    }
    canvas.translate(-view.left, -view.top);
}
 
Example #8
Source File: MultiResolutionSplashTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void testSplash(ImageInfo test) throws Exception {
    SplashScreen splashScreen = SplashScreen.getSplashScreen();

    if (splashScreen == null) {
        throw new RuntimeException("Splash screen is not shown!");
    }

    Graphics2D g = splashScreen.createGraphics();
    Rectangle splashBounds = splashScreen.getBounds();
    int screenX = (int) splashBounds.getCenterX();
    int screenY = (int) splashBounds.getCenterY();

    Robot robot = new Robot();
    Color splashScreenColor = robot.getPixelColor(screenX, screenY);

    float scaleFactor = getScaleFactor();
    Color testColor = (1 < scaleFactor) ? test.color2x : test.color1x;

    if (!compare(testColor, splashScreenColor)) {
        throw new RuntimeException(
                "Image with wrong resolution is used for splash screen!");
    }
}
 
Example #9
Source File: CyclicNumberAxis.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Selects a tick unit when the axis is displayed horizontally.
 *
 * @param g2  the graphics device.
 * @param drawArea  the drawing area.
 * @param dataArea  the data area.
 * @param edge  the side of the rectangle on which the axis is displayed.
 */
protected void selectHorizontalAutoTickUnit(Graphics2D g2,
        Rectangle2D drawArea, Rectangle2D dataArea, RectangleEdge edge) {

    double tickLabelWidth
        = estimateMaximumTickLabelWidth(g2, getTickUnit());

    // Compute number of labels
    double n = getRange().getLength()
               * tickLabelWidth / dataArea.getWidth();

    setTickUnit(
            (NumberTickUnit) getStandardTickUnits().getCeilingTickUnit(n),
            false, false);

 }
 
Example #10
Source File: MapRouteDrawer.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Draws a specified CursorImage if available.
 *
 * @param graphics The {@linkplain Graphics2D} Object being drawn on
 * @param routeDescription The RouteDescription object containing the CursorImage
 * @param lastRoutePoint The last {@linkplain Point2D} on the drawn Route as a center for the
 *     cursor icon.
 */
private void drawCustomCursor(
    final Graphics2D graphics,
    final RouteDescription routeDescription,
    final Point2D lastRoutePoint) {
  final BufferedImage cursorImage = (BufferedImage) routeDescription.getCursorImage();
  if (cursorImage != null) {
    for (final Point2D[] endPoint : routeCalculator.getAllPoints(lastRoutePoint)) {
      final AffineTransform imageTransform = getDrawingTransform();
      imageTransform.translate(endPoint[0].getX(), endPoint[0].getY());
      imageTransform.translate(cursorImage.getWidth() / 2.0, cursorImage.getHeight() / 2.0);
      imageTransform.scale(1 / mapPanel.getScale(), 1 / mapPanel.getScale());
      graphics.drawImage(cursorImage, imageTransform, null);
    }
  }
}
 
Example #11
Source File: IntervalBarRenderer.java    From opensim-gui with Apache License 2.0 6 votes vote down vote up
/**
 * Draws the bar for a single (series, category) data item.
 *
 * @param g2  the graphics device.
 * @param state  the renderer state.
 * @param dataArea  the data area.
 * @param plot  the plot.
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param dataset  the dataset.
 * @param row  the row index (zero-based).
 * @param column  the column index (zero-based).
 * @param pass  the pass index.
 */
public void drawItem(Graphics2D g2,
                     CategoryItemRendererState state,
                     Rectangle2D dataArea,
                     CategoryPlot plot,
                     CategoryAxis domainAxis,
                     ValueAxis rangeAxis,
                     CategoryDataset dataset,
                     int row,
                     int column,
                     int pass) {

     if (dataset instanceof IntervalCategoryDataset) {
         IntervalCategoryDataset d = (IntervalCategoryDataset) dataset;
         drawInterval(g2, state, dataArea, plot, domainAxis, rangeAxis, 
                 d, row, column);
     }
     else {
         super.drawItem(g2, state, dataArea, plot, domainAxis, rangeAxis, 
                 dataset, row, column, pass);
     } 
     
 }
 
Example #12
Source File: patch1-Chart-26-jMutRepair_patch1-Chart-26-jMutRepair_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Utility method for drawing a line perpendicular to the range axis (used
 * for crosshairs).
 *
 * @param g2  the graphics device.
 * @param dataArea  the area defined by the axes.
 * @param value  the data value.
 * @param stroke  the line stroke (<code>null</code> not permitted).
 * @param paint  the line paint (<code>null</code> not permitted).
 */
protected void drawRangeLine(Graphics2D g2, Rectangle2D dataArea,
        double value, Stroke stroke, Paint paint) {

    double java2D = getRangeAxis().valueToJava2D(value, dataArea, 
            getRangeAxisEdge());
    Line2D line = null;
    if (this.orientation == PlotOrientation.HORIZONTAL) {
        line = new Line2D.Double(java2D, dataArea.getMinY(), java2D, 
                dataArea.getMaxY());
    }
    else if (this.orientation == PlotOrientation.VERTICAL) {
        line = new Line2D.Double(dataArea.getMinX(), java2D, 
                dataArea.getMaxX(), java2D);
    }
    g2.setStroke(stroke);
    g2.setPaint(paint);
    g2.draw(line);

}
 
Example #13
Source File: SlidingTabDisplayerButtonUI.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Provides the painting logic.  Note that this does not call any of the
 * painting methods of BasicToggleButtonUI */
@Override
public final void paint(Graphics g, JComponent c) {
    
    BasicSlidingTabDisplayerUI.IndexButton b = 
        (BasicSlidingTabDisplayerUI.IndexButton) c;
    
    Graphics2D g2d = (Graphics2D) g;
    
    paintBackground (g2d, b);
    
    Object orientation = b.getOrientation();
    
    AffineTransform tr = g2d.getTransform();
    if (orientation == TabDisplayer.ORIENTATION_EAST) {
         g2d.rotate( Math.PI / 2 ); 
         g2d.translate( 0, - c.getWidth() );
    } else if (orientation == TabDisplayer.ORIENTATION_WEST) {
         g2d.rotate(-Math.PI / 2); 
         g2d.translate(-c.getHeight(), 0);
    }

    paintIconAndText (g2d, b, orientation);
    g2d.setTransform (tr);
}
 
Example #14
Source File: ButtonTabComponent.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void paintComponent (Graphics g)
{
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D) g.create();

    //shift the image for pressed buttons
    if (getModel().isPressed()) {
        g2.translate(1, 1);
    }

    g2.setStroke(new BasicStroke(2));

    if (getModel().isRollover()) {
        g2.setColor(Color.MAGENTA);
    } else {
        g2.setColor(Color.BLACK);
    }

    int delta = 4; // Margin around the cross
    g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
    g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
    g2.dispose();
}
 
Example #15
Source File: VisualCircuitConnection.java    From workcraft with MIT License 6 votes vote down vote up
@Override
public void draw(DrawRequest r) {
    // Draw a small pieces of line at the beginning and at the end of connection arc when the gate contacts are hidden.
    Graphics2D g = r.getGraphics();
    Decoration d = r.getDecoration();
    Color colorisation = d.getColorisation();
    g.setColor(ColorUtils.colorise(getColor(), colorisation));
    g.setStroke(new BasicStroke((float) CircuitSettings.getWireWidth()));

    boolean showContact = CircuitSettings.getShowContacts() || (d instanceof StateDecoration);

    if (!showContact && (getFirst().getParent() instanceof VisualCircuitComponent)) {
        double tStart = Geometry.getBorderPointParameter(getFirstShape(), getGraphic(), 0, 1);
        g.draw(new Line2D.Double(getFirstCenter(), getGraphic().getPointOnCurve(tStart)));
    }

    if (!showContact && (getSecond().getParent() instanceof VisualCircuitComponent)) {
        double tEnd = Geometry.getBorderPointParameter(getSecondShape(), getGraphic(), 1, 0);
        g.draw(new Line2D.Double(getGraphic().getPointOnCurve(tEnd), getSecondCenter()));
    }
}
 
Example #16
Source File: Renderer.java    From gpx-animator with Apache License 2.0 6 votes vote down vote up
private void printText(final Graphics2D g2, final String text, final float x, final float y) {
    final FontRenderContext frc = g2.getFontRenderContext();
    g2.setStroke(new BasicStroke(3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
    final int height = g2.getFontMetrics(font).getHeight();

    final String[] lines = text == null ? new String[0] : text.split("\n");
    float yy = y - (lines.length - 1) * height;
    for (final String line : lines) {
        if (!line.isEmpty()) {
            final TextLayout tl = new TextLayout(line, font, frc);
            final Shape sha = tl.getOutline(AffineTransform.getTranslateInstance(x, yy));
            g2.setColor(Color.white);
            g2.fill(sha);
            g2.draw(sha);

            g2.setFont(font);
            g2.setColor(Color.black);
            g2.drawString(line, x, yy);
        }

        yy += height;
    }
}
 
Example #17
Source File: OverlayUtil.java    From runelite with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void renderActorOverlayImage(Graphics2D graphics, Actor actor, BufferedImage image, Color color, int zOffset)
{
	Polygon poly = actor.getCanvasTilePoly();
	if (poly != null)
	{
		renderPolygon(graphics, poly, color);
	}

	Point imageLocation = actor.getCanvasImageLocation(image, zOffset);
	if (imageLocation != null)
	{
		renderImageLocation(graphics, imageLocation, image);
	}
}
 
Example #18
Source File: BEMenuItemUI.java    From beautyeye with Apache License 2.0 5 votes vote down vote up
@Override
protected void paintBackground(Graphics g, JMenuItem menuItem, Color bgColor)
{
	// see parent!
	ButtonModel model = menuItem.getModel();
	Color oldColor = g.getColor();
	int menuWidth = menuItem.getWidth();
	int menuHeight = menuItem.getHeight();
	
	Graphics2D g2 = (Graphics2D)g;
	
	if (model.isArmed()
			|| (menuItem instanceof JMenu && model.isSelected()))
	{
		//菜单项的样式绘制(用NinePatch图来填充)
		__Icon9Factory__.getInstance().getBgIcon_ItemSelected()
				.draw(g2, 0, 0, menuWidth, menuHeight);
	}
	else
	{
		if(!enforceTransparent)
		{
			g.setColor(menuItem.getBackground());
			g.fillRect(0, 0, menuWidth, menuHeight);
		}
	}
	g.setColor(oldColor);
}
 
Example #19
Source File: ProjectionProfile.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
protected void paintComponent(Graphics g) {
  Graphics2D g2 = (Graphics2D) g;

  Dimension size = getSize(null);

  g2.setColor(getBackground());
  g2.fillRect(0, 0, size.width, size.height);
  g2.setColor(Color.black);

  ProjectionProfile.this.paint(g2, direction, 0, 0);
}
 
Example #20
Source File: JSoftGraphBundle.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void paintNode(Graphics2D g, Node node) {
  if(node instanceof BundleNode) {
    BundleNode bn = (BundleNode)node;
    paintBundleNode(g, bundleSelModel, bn, hoverNode);
  } else if(node instanceof EmptyNode) {
    paintEmptyNode(g, bundleSelModel, node, hoverNode);
  }
}
 
Example #21
Source File: SimpleTextPaneResizeable.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Paint the text area
 */
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D graphics = (Graphics2D)g;
    if(inTheTriangleZone) {
        graphics.setColor(new Color(0.5f,0.5f,0.5f,0.75f));
    }
    else {
        graphics.setColor(new Color(0.5f,0.5f,0.5f,0.2f));
    }
    graphics.fillPolygon(getTriangle());
}
 
Example #22
Source File: StarmapScreen.java    From open-ig with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Draw the given rectangle onto the starmap.
 * @param g2 the graphics context
 * @param shape the shape
 * @param fill fill it?
 */
void drawShape(Graphics2D g2, Shape shape, boolean fill) {
	double zoom = getZoom();
	AffineTransform at = g2.getTransform();
	g2.translate(starmapRect.x, starmapRect.y);
	g2.scale(zoom, zoom);
	if (fill) {
		g2.fill(shape);
	} else {
		g2.draw(shape);
	}
	g2.setTransform(at);
}
 
Example #23
Source File: FlowArrangement.java    From ECG-Viewer with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Arranges the blocks without any constraints.  This puts all blocks
 * into a single row.
 *
 * @param container  the container.
 * @param g2  the graphics device.
 *
 * @return The size after the arrangement.
 */
protected Size2D arrangeNN(BlockContainer container, Graphics2D g2) {
    double x = 0.0;
    double width = 0.0;
    double maxHeight = 0.0;
    List blocks = container.getBlocks();
    int blockCount = blocks.size();
    if (blockCount > 0) {
        Size2D[] sizes = new Size2D[blocks.size()];
        for (int i = 0; i < blocks.size(); i++) {
            Block block = (Block) blocks.get(i);
            sizes[i] = block.arrange(g2, RectangleConstraint.NONE);
            width = width + sizes[i].getWidth();
            maxHeight = Math.max(sizes[i].height, maxHeight);
            block.setBounds(
                new Rectangle2D.Double(
                    x, 0.0, sizes[i].width, sizes[i].height
                )
            );
            x = x + sizes[i].width + this.horizontalGap;
        }
        if (blockCount > 1) {
            width = width + this.horizontalGap * (blockCount - 1);
        }
        if (this.verticalAlignment != VerticalAlignment.TOP) {
            for (int i = 0; i < blocks.size(); i++) {
                //Block b = (Block) blocks.get(i);
                if (this.verticalAlignment == VerticalAlignment.CENTER) {
                    //TODO: shift block down by half
                }
                else if (this.verticalAlignment
                        == VerticalAlignment.BOTTOM) {
                    //TODO: shift block down to bottom
                }
            }
        }
    }
    return new Size2D(width, maxHeight);
}
 
Example #24
Source File: XYPlot.java    From SIMVA-SoS with Apache License 2.0 5 votes vote down vote up
/**
 * Draws the gridlines for the plot's primary range axis, if they are
 * visible.
 *
 * @param g2  the graphics device.
 * @param area  the data area.
 * @param ticks  the ticks.
 *
 * @see #drawDomainGridlines(Graphics2D, Rectangle2D, List)
 */
protected void drawRangeGridlines(Graphics2D g2, Rectangle2D area,
                                  List ticks) {

    // no renderer, no gridlines...
    if (getRenderer() == null) {
        return;
    }

    // draw the range grid lines, if any...
    if (isRangeGridlinesVisible() || isRangeMinorGridlinesVisible()) {
        Stroke gridStroke = null;
        Paint gridPaint = null;
        ValueAxis axis = getRangeAxis();
        if (axis != null) {
            Iterator iterator = ticks.iterator();
            boolean paintLine;
            while (iterator.hasNext()) {
                paintLine = false;
                ValueTick tick = (ValueTick) iterator.next();
                if ((tick.getTickType() == TickType.MINOR)
                        && isRangeMinorGridlinesVisible()) {
                    gridStroke = getRangeMinorGridlineStroke();
                    gridPaint = getRangeMinorGridlinePaint();
                    paintLine = true;
                } else if ((tick.getTickType() == TickType.MAJOR)
                        && isRangeGridlinesVisible()) {
                    gridStroke = getRangeGridlineStroke();
                    gridPaint = getRangeGridlinePaint();
                    paintLine = true;
                }
                if ((tick.getValue() != 0.0
                        || !isRangeZeroBaselineVisible()) && paintLine) {
                    getRenderer().drawRangeLine(g2, this, getRangeAxis(),
                            area, tick.getValue(), gridPaint, gridStroke);
                }
            }
        }
    }
}
 
Example #25
Source File: PwaRegistry.java    From flow with Apache License 2.0 5 votes vote down vote up
private BufferedImage drawIconImage(BufferedImage baseImage, int bgColor,
        PwaIcon icon) {
    BufferedImage bimage = new BufferedImage(icon.getWidth(),
            icon.getHeight(), BufferedImage.TYPE_INT_ARGB);
    // Draw the image on to the buffered image
    Graphics2D graphics = bimage.createGraphics();

    // fill bg with fill-color
    graphics.setBackground(new Color(bgColor, true));
    graphics.clearRect(0, 0, icon.getWidth(), icon.getHeight());

    // calculate ratio (bigger ratio) for resize
    float ratio = (float) baseImage.getWidth()
            / (float) icon.getWidth() > (float) baseImage.getHeight()
                    / (float) icon.getHeight()
                            ? (float) baseImage.getWidth()
                                    / (float) icon.getWidth()
                            : (float) baseImage.getHeight()
                                    / (float) icon.getHeight();

    // Forbid upscaling of image
    ratio = ratio > 1.0f ? ratio : 1.0f;

    // calculate sizes with ratio
    int newWidth = Math.round(baseImage.getHeight() / ratio);
    int newHeight = Math.round(baseImage.getWidth() / ratio);

    // draw rescaled img in the center of created image
    graphics.drawImage(
            baseImage.getScaledInstance(newWidth, newHeight,
                    Image.SCALE_SMOOTH),
            (icon.getWidth() - newWidth) / 2,
            (icon.getHeight() - newHeight) / 2, null);
    graphics.dispose();
    return bimage;
}
 
Example #26
Source File: InstructionViewer.java    From aparapi with Apache License 2.0 5 votes vote down vote up
double foldPlace(Graphics2D _g, InstructionView _instructionView, double _x, double _y, boolean _dim) {
   _instructionView.dim = _dim;
   final FontMetrics fm = _g.getFontMetrics();

   _instructionView.label = InstructionHelper.getLabel(_instructionView.instruction, config.showPc, config.showExpressions,
         config.verboseBytecodeLabels);

   final int w = fm.stringWidth(_instructionView.label) + HMARGIN;
   final int h = fm.getHeight() + VMARGIN;

   double y = _y;
   final double x = _x + w + (_instructionView.instruction.getRootExpr() == _instructionView.instruction ? HGAP : HGAP);

   if (!config.collapseAll && !config.showExpressions) {

      for (Instruction e = _instructionView.instruction.getFirstChild(); e != null; e = e.getNextExpr()) {

         y = foldPlace(_g, getInstructionView(e), x, y, _dim);
         if (e != _instructionView.instruction.getLastChild()) {
            y += VGAP;
         }
      }

   }
   final double top = ((y + _y) / 2) - (h / 2);
   _instructionView.shape = new Rectangle((int) _x, (int) top, w, h);
   return (Math.max(_y, y));

}
 
Example #27
Source File: ThumbnailLabelUI.java    From pumpernickel with MIT License 5 votes vote down vote up
protected void paintText(Graphics2D g, JLabel label, String text,
		boolean isSelected, boolean isIndicated) {
	Font font = label.getFont();
	g.setFont(font);
	FontMetrics metrics = g.getFontMetrics(font);
	int limit = text.length();
	Rectangle2D r = g.getFontMetrics().getStringBounds(text, g);
	String finalText = text;
	while (limit > 0 && r.getWidth() > textRect.width) {
		limit--;
		finalText = text.substring(0, limit) + "...";
		r = g.getFontMetrics().getStringBounds(finalText, g);
	}
	g.drawString(finalText, textRect.x, textRect.y + metrics.getAscent());
}
 
Example #28
Source File: PathGraphics.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
protected PathGraphics(Graphics2D graphics, PrinterJob printerJob,
                       Printable painter, PageFormat pageFormat,
                       int pageIndex, boolean canRedraw) {
    super(graphics, printerJob);

    mPainter = painter;
    mPageFormat = pageFormat;
    mPageIndex = pageIndex;
    mCanRedraw = canRedraw;
}
 
Example #29
Source File: MyCursor.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override public void paint(Graphics gr) {
   gr.setColor(Color.GREEN);
   ((Graphics2D)gr).setStroke(new BasicStroke(3));
   //arrow
   gr.drawLine(0, 0, width/2, height/2);
   gr.drawLine(0, 0, width/2, 0);
   gr.drawLine(0, 0, 0, height/2);
   //plus
   gr.drawRect(width/2 - 1, height/2 -1, width/2 - 1, height/2 - 1);
   gr.drawLine(width*3/4 - 1, height/2 - 1, width*3/4 - 1, height);
   gr.drawLine(width/2 - 1, height*3/4 - 1, width, height*3/4 - 1);
}
 
Example #30
Source File: MyCursor.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override public void paint(Graphics gr) {
   gr.setColor(Color.GREEN);
   ((Graphics2D)gr).setStroke(new BasicStroke(3));
   //arrow
   gr.drawLine(0, 0, width/2, height/2);
   gr.drawLine(0, 0, width/2, 0);
   gr.drawLine(0, 0, 0, height/2);
   //plus
   gr.drawRect(width/2 - 1, height/2 -1, width/2 - 1, height/2 - 1);
   gr.drawLine(width*3/4 - 1, height/2 - 1, width*3/4 - 1, height);
   gr.drawLine(width/2 - 1, height*3/4 - 1, width, height*3/4 - 1);
}