Example usage for java.awt RenderingHints KEY_ANTIALIASING

List of usage examples for java.awt RenderingHints KEY_ANTIALIASING

Introduction

In this page you can find the example usage for java.awt RenderingHints KEY_ANTIALIASING.

Prototype

Key KEY_ANTIALIASING

To view the source code for java.awt RenderingHints KEY_ANTIALIASING.

Click Source Link

Document

Antialiasing hint key.

Usage

From source file:business.ImageManager.java

public void doDrawCircle(Graphics2D big, int x, int y, Color color) {
    //setup para os rastros
    big.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    big.setStroke(new BasicStroke());
    big.setColor(color);//from   w w w. j av a2  s  . c o  m

    //draw on graph
    big.drawOval(x, x, y, y);
}

From source file:org.jas.util.ImageUtils.java

public Image resize(Image image, int width, int height) {
    BufferedImage bufferedImage = (BufferedImage) image;
    int type = bufferedImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : bufferedImage.getType();
    BufferedImage resizedImage = new BufferedImage(width, height, type);
    Graphics2D g = resizedImage.createGraphics();
    g.setComposite(AlphaComposite.Src);

    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.drawImage(image, 0, 0, width, height, null);
    g.dispose();//from  w  w w .  ja va2s.com
    return resizedImage;
}

From source file:com.salesmanager.core.util.ProductImageUtil.java

public BufferedImage resize(BufferedImage image, int width, int height) {
    int type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image.getType();
    BufferedImage resizedImage = new BufferedImage(width, height, type);
    Graphics2D g = resizedImage.createGraphics();
    g.setComposite(AlphaComposite.Src);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.drawImage(image, 0, 0, width, height, null);
    g.dispose();/*from  w  ww .j a va 2  s . c om*/
    return resizedImage;
}

From source file:org.eclipse.titanium.graph.visualization.GraphHandler.java

/**
 * Exports the graph set for this class to a PNG file
 * //from ww w  .  ja  va2  s  .c om
 * @param path
 *            : The PNG file's path
 * @param mode
 *            : The way of export, see {@link GraphHandler}
 *            <code>public static</code> fields for possible values (EXPORT_
 *            named fields)
 * @param size
 *            : This parameter sets the size of the exported image in pixels
 * @throws Exception
 *             on file handling error
 */
public void saveToImage(final String path, final ImageExportType mode) throws BadLayoutException {
    if (layout == null || actVisualisator == null) {
        throw new BadLayoutException("Either the layout or the visuaizer is not set (is null)",
                ErrorType.NO_OBJECT);
    }

    VisualizationViewer<NodeDescriptor, EdgeDescriptor> tempVisualisator = null;
    Dimension size = null;
    switch (mode) {
    case EXPORT_SEEN_GRAPH: {
        tempVisualisator = actVisualisator;
        size = actVisualisator.getPreferredSize();
    }
        break;
    case EXPORT_WHOLE_GRAPH: {
        layout = actVisualisator.getGraphLayout();
        if (size == null) {
            size = new Dimension(layout.getSize().width, layout.getSize().height);
        }

        final Transformer<NodeDescriptor, Point2D> trf = new Transformer<NodeDescriptor, Point2D>() {
            @Override
            public Point2D transform(final NodeDescriptor v) {
                return layout.transform(v);
            }
        };

        tempVisualisator = new VisualizationViewer<NodeDescriptor, EdgeDescriptor>(
                new LayoutBuilder(g, Layouts.LAYOUT_STATIC, size).transformer(trf).build());
        tempVisualisator.setPreferredSize(size);
        tempVisualisator.setSize(size);
        tempVisualisator.getRenderContext().setVertexLabelTransformer(NODE_LABELER);

        final GraphRenderer<NodeDescriptor, EdgeDescriptor> rnd = new GraphRenderer<NodeDescriptor, EdgeDescriptor>(
                NODE_LABELER, tempVisualisator.getPickedVertexState(), tempVisualisator.getPickedEdgeState());
        setNodeRenderer(rnd, tempVisualisator);
        tempVisualisator.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
        tempVisualisator.setBackground(Color.white);
        tempVisualisator.setDoubleBuffered(false);
    }
        break;
    case EXPORT_SATELLITE: {
        tempVisualisator = satView;
        size = tempVisualisator.getSize();
    }
        break;
    default:
        ErrorReporter.logError("Unexpected image export type " + mode);
        return;
    }

    BufferedImage image;
    final GUIErrorHandler errorHandler = new GUIErrorHandler();
    try {
        image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
    } catch (OutOfMemoryError e) {
        final long needed = (long) size.width * (long) size.height * 4;
        String temp;
        if (needed < 1024) {
            temp = needed + " bytes";
        } else if (needed < 1024 * 1024) {
            temp = needed / 1024 + " Kbytes";
        } else {
            temp = needed / 1024 / 1024 + " Mbytes";
        }
        final String errorText = "Could not save an image of " + size.width + "*" + size.height
                + " size as there was not enough free memory (" + temp + ")";
        errorHandler.reportErrorMessage(errorText);
        ErrorReporter.logExceptionStackTrace(errorText, e);
        return;
    }
    final Graphics2D g2 = image.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    tempVisualisator.paint(g2);
    g2.dispose();
    try {
        ImageIO.write(image, "png", new File(path));
    } catch (IOException e) {
        final String message = "Error while writing to file" + path;
        ErrorReporter.logExceptionStackTrace(message, e);
        errorHandler.reportException(message, e);
    }
}

From source file:ala.soils2sat.DrawingUtils.java

public static void drawRoundedRect(Graphics g, int left, int top, int right, int bottom) {
    Graphics2D g2d = (Graphics2D) g;
    g.drawLine(left + cornerSize, top, right - cornerSize, top);
    g.drawLine(left + cornerSize, bottom, right - cornerSize, bottom);
    g.drawLine(left, top + cornerSize, left, bottom - cornerSize);
    g.drawLine(right, top + cornerSize, right, bottom - cornerSize);
    final Object previousAntiAliasingHint = g2d.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
    final Stroke previousStroke = g2d.getStroke();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
    try {/*  w ww.j av  a  2  s  .c  o m*/
        g.drawLine(left, top + cornerSize, left + cornerSize, top);
        g.drawLine(left, bottom - cornerSize, left + cornerSize, bottom);
        g.drawLine(right, top + cornerSize, right - cornerSize, top);
        g.drawLine(right, bottom - cornerSize, right - cornerSize, bottom);
    } finally {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, previousAntiAliasingHint);
        g2d.setStroke(previousStroke);
    }
}

From source file:com.AandR.beans.plotting.imagePlotPanel.CanvasPanel.java

/**
 *
 *///from w w w .j  a  v  a  2  s . co  m
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    setBackground(Color.GRAY);
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    if (bufferedImage != null) {
        scaleGraphicsContext(g2);
        g2.drawImage(bufferedImage, 0, 0, null);
        drawTextBoxes(g2);
    }
}

From source file:anl.verdi.plot.jfree.XYBlockRenderer.java

/**
 * Draws the block representing the specified item.
 *
 * @param g2             the graphics device.
 * @param state          the state.//from   w  w  w .  j a  v  a 2 s. c o  m
 * @param dataArea       the data area.
 * @param info           the plot rendering info.
 * @param plot           the plot.
 * @param domainAxis     the x-axis.
 * @param rangeAxis      the y-axis.
 * @param dataset        the dataset.
 * @param series         the series index.
 * @param item           the item index.
 * @param crosshairState the crosshair state.
 * @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) {

    double x = dataset.getXValue(series, item);
    double y = dataset.getYValue(series, item);
    double z = 0.0;
    double max = paintScale.getUpperBound();
    double min = paintScale.getLowerBound();

    if (dataset instanceof XYZDataset)
        z = ((XYZDataset) dataset).getZValue(series, item);

    //NOTE: so to get the max/min color instead of unknown (Qun He, UNC, 03/19/2009)
    if (z > max)
        z = max;

    if (z < min)
        z = min;

    Color p = (Color) this.paintScale.getPaint(z);

    double xx0 = domainAxis.valueToJava2D(x + this.xOffset, dataArea, plot.getDomainAxisEdge());
    double yy0 = rangeAxis.valueToJava2D(y + this.yOffset, dataArea, plot.getRangeAxisEdge());
    double xx1 = domainAxis.valueToJava2D(x + this.blockWidth + this.xOffset, dataArea,
            plot.getDomainAxisEdge());
    double yy1 = rangeAxis.valueToJava2D(y + this.blockHeight + this.yOffset, dataArea,
            plot.getRangeAxisEdge());
    Rectangle2D block;
    PlotOrientation orientation = plot.getOrientation();
    if (orientation.equals(PlotOrientation.HORIZONTAL)) {
        block = new Rectangle2D.Double(Math.min(yy0, yy1), Math.min(xx0, xx1), Math.abs(yy1 - yy0),
                Math.abs(xx0 - xx1));
    } else {
        block = new Rectangle2D.Double(Math.min(xx0, xx1), Math.min(yy0, yy1), Math.abs(xx1 - xx0),
                Math.abs(yy1 - yy0));
    }
    g2.setColor(p);
    g2.fill(block);

    if (gridLinesEnabled) {
        boolean aaOn = false;
        if (g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING) == RenderingHints.VALUE_ANTIALIAS_ON) {
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
            aaOn = true;
        }
        g2.setPaint(gridLineColor);
        g2.setStroke(gridLineStroke);
        g2.draw(block);
        if (aaOn)
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    } else {
        g2.setStroke(basicStroke);
        g2.draw(block);
    }
}

From source file:com.salesmanager.core.util.ProductImageUtil.java

public BufferedImage blurImage(BufferedImage image) {
    float ninth = 1.0f / 9.0f;
    float[] blurKernel = { ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth };
    Map<Key, Object> map = new HashMap<Key, Object>();
    map.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    map.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    map.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    RenderingHints hints = new RenderingHints(map);
    BufferedImageOp op = new ConvolveOp(new Kernel(3, 3, blurKernel), ConvolveOp.EDGE_NO_OP, hints);
    return op.filter(image, null);
}

From source file:savant.view.swing.GraphPane.java

public boolean render(Graphics2D g2, Range xRange, Range yRange) {
    LOG.trace("GraphPane.render(g2, " + xRange + ", " + yRange + ")");
    double oldUnitHeight = unitHeight;
    int oldYMax = yMax;

    // Paint a gradient from top to bottom
    GradientPaint gp0 = new GradientPaint(0, 0, ColourSettings.getColor(ColourKey.GRAPH_PANE_BACKGROUND_TOP), 0,
            getHeight(), ColourSettings.getColor(ColourKey.GRAPH_PANE_BACKGROUND_BOTTOM));
    g2.setPaint(gp0);//w w  w .  j av  a2  s .  com
    g2.fillRect(0, 0, getWidth(), getHeight());

    GraphPaneController gpc = GraphPaneController.getInstance();
    LocationController lc = LocationController.getInstance();
    JScrollBar scroller = getVerticalScrollBar();

    if (gpc.isPanning() && !isLocked()) {

        double fromX = transformXPos(gpc.getMouseClickPosition());
        double toX = transformXPos(gpc.getMouseReleasePosition());
        g2.translate(toX - fromX, 0);
    }

    // Deal with the progress-bar.
    if (tracks == null) {
        parentFrame.updateProgress();
        return false;
    } else {
        for (Track t : tracks) {
            if (t.getRenderer().isWaitingForData()) {
                String progressMsg = (String) t.getRenderer().getInstruction(DrawingInstruction.PROGRESS);
                setPreferredSize(new Dimension(getWidth(), 0));
                showProgress(progressMsg, -1.0);
                return false;
            }
        }
    }
    if (progressPanel != null) {
        remove(progressPanel);
        progressPanel = null;
    }

    int minYRange = Integer.MAX_VALUE;
    int maxYRange = Integer.MIN_VALUE;
    AxisType bestYAxis = AxisType.NONE;
    for (Track t : tracks) {

        // ask renderers for extra info on range; consolidate to maximum Y range
        AxisRange axisRange = (AxisRange) t.getRenderer().getInstruction(DrawingInstruction.AXIS_RANGE);

        if (axisRange != null) {
            int axisYMin = axisRange.getYMin();
            int axisYMax = axisRange.getYMax();
            if (axisYMin < minYRange) {
                minYRange = axisYMin;
            }
            if (axisYMax > maxYRange) {
                maxYRange = axisYMax;
            }
        }

        // Ask renderers if they want horizontal grid-lines; if any say yes, draw them.
        switch (t.getYAxisType(t.getResolution(xRange))) {
        case INTEGER_GRIDLESS:
            if (bestYAxis == AxisType.NONE) {
                bestYAxis = AxisType.INTEGER_GRIDLESS;
            }
            break;
        case INTEGER:
            if (bestYAxis != AxisType.REAL) {
                bestYAxis = AxisType.INTEGER;
            }
            break;
        case REAL:
            bestYAxis = AxisType.REAL;
            break;
        }
    }

    setXAxisType(tracks[0].getXAxisType(tracks[0].getResolution(xRange)));
    setXRange(xRange);
    setYAxisType(bestYAxis);
    Range consolidatedYRange = new Range(minYRange, maxYRange);

    setYRange(consolidatedYRange);
    consolidatedYRange = new Range(yMin, yMax);

    DrawingMode currentMode = tracks[0].getDrawingMode();

    boolean sameRange = (prevRange != null && xRange.equals(prevRange));
    if (!sameRange) {
        PopupPanel.hidePopup();
    }
    boolean sameMode = currentMode == prevMode;
    boolean sameSize = prevSize != null && getSize().equals(prevSize)
            && parentFrame.getFrameLandscape().getWidth() == oldWidth
            && parentFrame.getFrameLandscape().getHeight() == oldHeight;
    boolean sameRef = prevRef != null && lc.getReferenceName().equals(prevRef);
    boolean withinScrollBounds = bufferedImage != null && scroller.getValue() >= getOffset()
            && scroller.getValue() < getOffset() + getViewportHeight() * 2;

    //bufferedImage stores the current graphic for future use. If nothing
    //has changed in the track since the last render, bufferedImage will
    //be used to redraw the current view. This method allows for fast repaints
    //on tracks where nothing has changed (panning, selection, plumbline,...)

    //if nothing has changed draw buffered image
    if (sameRange && sameMode && sameSize && sameRef && !renderRequired && withinScrollBounds) {
        g2.drawImage(bufferedImage, 0, getOffset(), this);
        renderCurrentSelected(g2);

        //force unitHeight from last render
        unitHeight = oldUnitHeight;
        yMax = oldYMax;

    } else {
        // Otherwise prepare for new render.
        renderRequired = false;

        int h = getHeight();
        if (!forcedHeight) {
            h = Math.min(h, getViewportHeight() * 3);
        }
        LOG.debug("Requesting " + getWidth() + "\u00D7" + h + " bufferedImage.");
        bufferedImage = new BufferedImage(getWidth(), h, BufferedImage.TYPE_INT_RGB);
        if (bufferedImage.getHeight() == getHeight()) {
            setOffset(0);
        } else {
            setOffset(scroller.getValue() - getViewportHeight());
        }
        LOG.debug("Rendering fresh " + bufferedImage.getWidth() + "\u00D7" + bufferedImage.getHeight()
                + " bufferedImage at (0, " + getOffset() + ")");

        Graphics2D g3 = bufferedImage.createGraphics();
        g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        prevRange = xRange;
        prevSize = getSize();
        prevMode = tracks[0].getDrawingMode();
        prevRef = lc.getReferenceName();

        renderBackground(g3, xAxisType == AxisType.INTEGER || xAxisType == AxisType.REAL,
                yAxisType == AxisType.INTEGER || yAxisType == AxisType.REAL);

        // Call the actual render() methods.
        boolean nothingRendered = true;
        String message = null;
        int priority = -1;

        for (Track t : tracks) {
            // Change renderers' drawing instructions to reflect consolidated YRange
            AxisRange axes = (AxisRange) t.getRenderer().getInstruction(DrawingInstruction.AXIS_RANGE);

            if (axes == null) {
                axes = new AxisRange(xRange, consolidatedYRange);
            } else {
                axes = new AxisRange(axes.getXRange(), consolidatedYRange);
            }

            //System.out.println("Consolidated y range for " + t.getName() + " is " + consolidatedYRange);
            t.getRenderer().addInstruction(DrawingInstruction.AXIS_RANGE, axes);

            try {
                t.getRenderer().render(g3, this);
                nothingRendered = false;
            } catch (RenderingException rx) {
                if (rx.getPriority() > priority) {
                    // If we have more than one message with the same priority, the first one will end up being drawn.
                    message = rx.getMessage();
                    priority = rx.getPriority();
                }
            } catch (Throwable x) {
                // Renderer itself threw an exception.
                LOG.error("Error rendering " + t, x);
                message = MiscUtils.getMessage(x);
                priority = RenderingException.ERROR_PRIORITY;
            }
        }
        if (nothingRendered && message != null) {
            setPreferredSize(new Dimension(getWidth(), 0));
            revalidate();
            drawMessage(g3, message);
        }

        updateYMax();

        // If a change has occured that affects scrollbar...
        if (paneResize) {
            paneResize = false;

            // Change size of current frame
            if (getHeight() != newHeight) {
                Dimension newSize = new Dimension(getWidth(), newHeight);
                setPreferredSize(newSize);
                setSize(newSize);
                parentFrame.validate(); // Ensures that scroller.getMaximum() is up to date.

                // If pane is resized, scrolling always starts at the bottom.  The only place
                // where looks wrong is when we have a continuous track with negative values.
                scroller.setValue(scroller.getMaximum());
                repaint();
                return false;
            }
        } else if (oldViewHeight != -1 && oldViewHeight != getViewportHeight()) {
            int newViewHeight = getViewportHeight();
            int oldScroll = scroller.getValue();
            scroller.setValue(oldScroll + (oldViewHeight - newViewHeight));
            oldViewHeight = newViewHeight;
        }
        oldWidth = parentFrame.getFrameLandscape().getWidth();
        oldHeight = parentFrame.getFrameLandscape().getHeight();

        g2.drawImage(bufferedImage, 0, getOffset(), this);
        fireExportEvent(xRange, bufferedImage);

        renderCurrentSelected(g2);
    }
    return true;
}

From source file:org.apache.pdfbox.pdfviewer.PageDrawer.java

/**
 * Stroke the path.//from w  ww. j  a  va 2  s.com
 *
 * @throws IOException If there is an IO error while stroking the path.
 */
public void strokePath() throws IOException {
    graphics.setComposite(getGraphicsState().getStrokeJavaComposite());
    Paint strokingPaint = getGraphicsState().getStrokingColor().getJavaColor();
    if (strokingPaint == null) {
        strokingPaint = getGraphicsState().getStrokingColor().getPaint(pageSize.height);
    }
    if (strokingPaint == null) {
        LOG.info("ColorSpace " + getGraphicsState().getStrokingColor().getColorSpace().getName()
                + " doesn't provide a stroking color, using white instead!");
        strokingPaint = Color.WHITE;
    }
    graphics.setPaint(strokingPaint);
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
    graphics.setClip(getGraphicsState().getCurrentClippingPath());
    GeneralPath path = getLinePath();
    graphics.draw(path);
    path.reset();
}