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:test.be.fedict.eid.applet.JGraphTest.java

private void graphToFile(BasicVisualizationServer<String, String> visualization, File file) throws IOException {
    Dimension size = visualization.getSize();
    int width = (int) (size.getWidth() + 1);
    int height = (int) (size.getHeight() + 1);
    LOG.debug("width: " + width);
    LOG.debug("height: " + height);
    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = bufferedImage.createGraphics();
    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, 900, 650);// www  . jav  a2 s.co m
    visualization.setBounds(0, 0, 900, 650);
    visualization.paint(graphics);
    graphics.dispose();
    ImageIO.write(bufferedImage, "png", file);
}

From source file:net.sf.maltcms.chromaui.annotations.PeakAnnotationRenderer.java

private void drawOutline(Shape entity, Graphics2D g2, Color fill, Color stroke, ChartPanel chartPanel,
        boolean scale, float alpha) {
    if (entity != null) {
        //System.out.println("Drawing entity with bbox: "+entity.getBounds2D());
        Shape savedClip = g2.getClip();
        Rectangle2D dataArea = chartPanel.getScreenDataArea();
        Color c = g2.getColor();// w ww .  j  a v a 2  s.  com
        Composite comp = g2.getComposite();
        g2.clip(dataArea);
        g2.setColor(fill);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        JFreeChart chart = chartPanel.getChart();
        XYPlot plot = (XYPlot) chart.getPlot();
        ValueAxis xAxis = plot.getDomainAxis();
        ValueAxis yAxis = plot.getRangeAxis();
        RectangleEdge xAxisEdge = plot.getDomainAxisEdge();
        RectangleEdge yAxisEdge = plot.getRangeAxisEdge();
        Rectangle2D entityBounds = entity.getBounds2D();
        double viewX = xAxis.valueToJava2D(entityBounds.getCenterX(), dataArea, xAxisEdge);
        double viewY = yAxis.valueToJava2D(entityBounds.getCenterY(), dataArea, yAxisEdge);
        double viewW = xAxis.lengthToJava2D(entityBounds.getWidth(), dataArea, xAxisEdge);
        double viewH = yAxis.lengthToJava2D(entityBounds.getHeight(), dataArea, yAxisEdge);
        PlotOrientation orientation = plot.getOrientation();

        //transform model to origin (0,0) in model coordinates
        AffineTransform toOrigin = AffineTransform.getTranslateInstance(-entityBounds.getCenterX(),
                -entityBounds.getCenterY());
        //transform from origin (0,0) to model location
        AffineTransform toModelLocation = AffineTransform.getTranslateInstance(entityBounds.getCenterX(),
                entityBounds.getCenterY());
        //transform from model scale to view scale
        double scaleX = viewW / entityBounds.getWidth();
        double scaleY = viewH / entityBounds.getHeight();
        Logger.getLogger(getClass().getName()).log(Level.FINE, "Scale x: {0} Scale y: {1}",
                new Object[] { scaleX, scaleY });
        AffineTransform toViewScale = AffineTransform.getScaleInstance(scaleX, scaleY);
        AffineTransform toViewLocation = AffineTransform.getTranslateInstance(viewX, viewY);
        AffineTransform flipTransform = AffineTransform.getScaleInstance(1.0f, -1.0f);
        AffineTransform modelToView = new AffineTransform(toOrigin);
        modelToView.preConcatenate(flipTransform);
        modelToView.preConcatenate(toViewScale);
        modelToView.preConcatenate(toViewLocation);
        //
        //            if (orientation == PlotOrientation.HORIZONTAL) {
        //                entity = ShapeUtilities.createTranslatedShape(entity, viewY,
        //                        viewX);
        //            } else if (orientation == PlotOrientation.VERTICAL) {
        //                entity = ShapeUtilities.createTranslatedShape(entity, viewX,
        //                        viewY);
        //            }
        FlatteningPathIterator iter = new FlatteningPathIterator(modelToView.createTransformedShape(entity)
                .getPathIterator(AffineTransform.getTranslateInstance(0, 0)), 5);
        Path2D.Float path = new Path2D.Float();
        path.append(iter, false);

        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        g2.fill(path);
        if (stroke != null) {
            g2.setColor(stroke);
            g2.draw(path);
        }
        g2.setComposite(comp);
        g2.setColor(c);
        g2.setClip(savedClip);
    } else {
        Logger.getLogger(getClass().getName()).info("Entity is null!");
    }
}

From source file:org.polymap.core.data.feature.FeatureRenderProcessor2.java

protected Image getMap(final Set<ILayer> layers, int width, int height, final ReferencedEnvelope bbox) {
    //        Logger wfsLog = Logging.getLogger( "org.geotools.data.wfs.protocol.http" );
    //        wfsLog.setLevel( Level.FINEST );

    // mapContext
    MapContext mapContext = mapContextRef.get(new Supplier<MapContext>() {
        public MapContext get() {
            log.debug("Creating new MapContext... ");
            // sort z-priority
            TreeMap<String, ILayer> sortedLayers = new TreeMap();
            for (ILayer layer : layers) {
                String uniqueOrderKey = String.valueOf(layer.getOrderKey()) + layer.id();
                sortedLayers.put(uniqueOrderKey, layer);
            }//from  w  ww.ja v  a  2 s.c om
            // add to mapContext
            MapContext result = new DefaultMapContext(bbox.getCoordinateReferenceSystem());
            for (ILayer layer : sortedLayers.values()) {
                try {
                    FeatureSource fs = PipelineFeatureSource.forLayer(layer, false);
                    log.debug("        FeatureSource: " + fs);
                    log.debug("            fs.getName(): " + fs.getName());

                    Style style = layer.getStyle().resolve(Style.class, null);
                    if (style == null) {
                        log.warn("            fs.getName(): " + fs.getName());
                        style = new DefaultStyles().findStyle(fs);
                    }
                    result.addLayer(fs, style);

                    // watch layer for style changes
                    LayerStyleListener listener = new LayerStyleListener(mapContextRef);
                    if (watchedLayers.putIfAbsent(layer, listener) == null) {
                        layer.addPropertyChangeListener(listener);
                    }
                } catch (IOException e) {
                    log.warn(e);
                    // FIXME set layer status and statusMessage
                } catch (PipelineIncubationException e) {
                    log.warn("No pipeline.", e);
                }
            }
            log.debug("created: " + result);
            return result;
        }
    });
    log.debug("using: " + mapContext);

    // render
    //        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    //        GraphicsConfiguration gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
    //        VolatileImage result = gc.createCompatibleVolatileImage( width, height, Transparency.TRANSLUCENT );

    BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    result.setAccelerationPriority(1);

    final Graphics2D g = result.createGraphics();
    //        log.info( "IMAGE: accelerated=" + result.getCapabilities( g.getDeviceConfiguration() ).isAccelerated() );

    try {
        final StreamingRenderer renderer = new StreamingRenderer();

        // rendering hints
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_SPEED);
        hints.add(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
        hints.add(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON));

        renderer.setJava2DHints(hints);
        //            g.setRenderingHints( hints );

        // error handler
        renderer.addRenderListener(new RenderListener() {
            int featureCount = 0;

            @Override
            public void featureRenderer(SimpleFeature feature) {
                //                  if (++featureCount == 100) {
                //                      log.info( "Switch off antialiasing!" );
                //                      RenderingHints off = new RenderingHints(
                //                              RenderingHints.KEY_ANTIALIASING,
                //                              RenderingHints.VALUE_ANTIALIAS_OFF );
                //                      renderer.setJava2DHints( off );
                //                      g.setRenderingHints( off );
                //                  }
            }

            @Override
            public void errorOccurred(Exception e) {
                log.error("Renderer error: ", e);
                drawErrorMsg(g, "Fehler bei der Darstellung.", e);
            }
        });

        // render params
        Map rendererParams = new HashMap();
        rendererParams.put("optimizedDataLoadingEnabled", Boolean.TRUE);
        renderer.setRendererHints(rendererParams);

        renderer.setContext(mapContext);
        Rectangle paintArea = new Rectangle(width, height);
        renderer.paint(g, paintArea, bbox);
        return result;
    } catch (Throwable e) {
        log.error("Renderer error: ", e);
        drawErrorMsg(g, null, e);
        return result;
    } finally {
        if (g != null) {
            g.dispose();
        }
    }
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private void drawInformationBox(Graphics2D g2, Activities activities, Rectangle2D rect, List<String> params,
        List<String> values, String totalParam, double totalValue, Color background_color, Color border_color) {
    final Font oldFont = g2.getFont();
    final Font paramFont = oldFont;
    final FontMetrics paramFontMetrics = g2.getFontMetrics(paramFont);
    final Font valueFont = oldFont.deriveFont(oldFont.getStyle() | Font.BOLD, (float) oldFont.getSize() + 1);
    final FontMetrics valueFontMetrics = g2.getFontMetrics(valueFont);
    final Font dateFont = oldFont.deriveFont((float) oldFont.getSize() - 1);
    final FontMetrics dateFontMetrics = g2.getFontMetrics(dateFont);

    final int x = (int) rect.getX();
    final int y = (int) rect.getY();
    final int width = (int) rect.getWidth();
    final int height = (int) rect.getHeight();

    final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
    final Composite oldComposite = g2.getComposite();
    final Color oldColor = g2.getColor();

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(border_color);/*from www .  j  a v a2 s  .  c  o m*/
    g2.drawRoundRect(x - 1, y - 1, width + 1, height + 1, 15, 15);
    g2.setColor(background_color);
    g2.setComposite(Utils.makeComposite(0.75f));
    g2.fillRoundRect(x, y, width, height, 15, 15);
    g2.setComposite(oldComposite);
    g2.setColor(oldColor);

    final Date date = activities.getDate().getTime();
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy");
    final String dateString = simpleDateFormat.format(date);

    final int padding = 5;

    int yy = y + padding + dateFontMetrics.getAscent();
    g2.setFont(dateFont);
    g2.setColor(COLOR_BLUE);
    g2.drawString(dateString, ((width - dateFontMetrics.stringWidth(dateString)) >> 1) + x, yy);

    int index = 0;
    final int dateInfoHeightMargin = 5;
    final int infoTotalHeightMargin = 5;
    final int paramValueHeightMargin = 0;

    yy += dateFontMetrics.getDescent() + dateInfoHeightMargin
            + Math.max(paramFontMetrics.getAscent(), valueFontMetrics.getAscent());
    for (String param : params) {
        final String value = values.get(index++);
        g2.setColor(Color.BLACK);
        g2.setFont(paramFont);
        g2.drawString(param + ":", padding + x, yy);
        g2.setFont(valueFont);
        g2.drawString(value, width - padding - valueFontMetrics.stringWidth(value) + x, yy);
        // Same as yy += valueFontMetrics.getDescent() + paramValueHeightMargin + valueFontMetrics.getAscent()
        yy += paramValueHeightMargin + Math.max(paramFontMetrics.getHeight(), valueFontMetrics.getHeight());
    }

    if (values.size() > 1) {
        yy -= paramValueHeightMargin;
        yy += infoTotalHeightMargin;
        if (totalValue > 0.0) {
            g2.setColor(JStockOptions.DEFAULT_HIGHER_NUMERICAL_VALUE_FOREGROUND_COLOR);
        } else if (totalValue < 0.0) {
            g2.setColor(JStockOptions.DEFAULT_LOWER_NUMERICAL_VALUE_FOREGROUND_COLOR);
        }

        g2.setFont(paramFont);
        g2.drawString(totalParam + ":", padding + x, yy);
        g2.setFont(valueFont);
        final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace();
        final String totalValueStr = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace,
                totalValue);
        g2.drawString(totalValueStr, width - padding - valueFontMetrics.stringWidth(totalValueStr) + x, yy);
    }

    g2.setColor(oldColor);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias);
    g2.setFont(oldFont);
}

From source file:org.tros.logo.swing.LogoPanel.java

@Override
public void setXY(final double x, final double y) {
    Drawable command = new Drawable() {

        @Override//from   w ww . j  av a  2 s  .  c  o  m
        public void draw(Graphics2D g2, TurtleState turtleState) {
            double x2 = (turtleState.width > 0 ? turtleState.width : getWidth()) / 2.0 + x;
            double y2 = (turtleState.height > 0 ? turtleState.height : getHeight()) / 2.0 + y;

            if (!turtleState.penup) {
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.draw(new Line2D.Double(turtleState.penX, turtleState.penY, x2, y2));
            }
            turtleState.penX = x2;
            turtleState.penY = y2;
        }

        @Override
        public void addListener(DrawListener listener) {
        }

        @Override
        public void removeListener(DrawListener listener) {
        }

        @Override
        public Drawable cloneDrawable() {
            return this;
        }
    };
    submitCommand(command);
}

From source file:org.eclipse.birt.chart.device.g2d.G2dRendererBase.java

protected void prepareGraphicsContext() {
    _g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    _g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    getDisplayServer().setGraphicsContext(_g2d);
}

From source file:net.technicpack.ui.lang.ResourceLoader.java

public BufferedImage getCircleClippedImage(BufferedImage contentImage) {
    // copy the picture to an image with transparency capabilities
    BufferedImage outputImage = new BufferedImage(contentImage.getWidth(), contentImage.getHeight(),
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = (Graphics2D) outputImage.getGraphics();
    g2.drawImage(contentImage, 0, 0, null);

    // Create the area around the circle to cut out
    Area cutOutArea = new Area(new Rectangle(0, 0, outputImage.getWidth(), outputImage.getHeight()));

    int diameter = (outputImage.getWidth() < outputImage.getHeight()) ? outputImage.getWidth()
            : outputImage.getHeight();/*  ww  w.j ava  2s.  c o  m*/
    cutOutArea.subtract(new Area(new Ellipse2D.Float((outputImage.getWidth() - diameter) / 2,
            (outputImage.getHeight() - diameter) / 2, diameter, diameter)));

    // Set the fill color to an opaque color
    g2.setColor(Color.WHITE);
    // Set the composite to clear pixels
    g2.setComposite(AlphaComposite.Clear);
    // Turn on antialiasing
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // Clear the cut out area
    g2.fill(cutOutArea);

    // dispose of the graphics object
    g2.dispose();

    return outputImage;
}

From source file:eu.udig.style.advanced.utils.Utilities.java

/**
 * Creates an image from a set of {@link RuleWrapper}s.
 * /*from  w w w . ja  va2s .  com*/
 * @param ruleWrapperList the list of rule wrappers.
 * @param width the image width.
 * @param height the image height.
 * @return the new created {@link BufferedImage}.
 */
public static BufferedImage pointRulesWrapperToImage(final List<RuleWrapper> ruleWrapperList, int width,
        int height) {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = image.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    for (RuleWrapper ruleWrapper : ruleWrapperList) {
        BufferedImage tmpImage = Utilities.pointRuleWrapperToImage(ruleWrapper, width, height);
        g2d.drawImage(tmpImage, 0, 0, null);
    }
    g2d.dispose();
    return image;
}

From source file:org.vulpe.view.tags.Functions.java

/**
 * This method takes in an image as a byte array (currently supports GIF,
 * JPG, PNG and possibly other formats) and resizes it to have a width no
 * greater than the pMaxWidth parameter in pixels. It converts the image to
 * a standard quality JPG and returns the byte array of that JPG image.
 *
 * @param imageData//from  ww  w  .  j a v a2 s  . c o m
 *            the image data.
 * @param maxWidth
 *            the max width in pixels, 0 means do not scale.
 * @return the resized JPG image.
 * @throws IOException
 *             if the image could not be manipulated correctly.
 */
public static byte[] resizeImageAsJPG(final byte[] imageData, final int maxWidth) throws IOException {
    // Create an ImageIcon from the image data
    final ImageIcon imageIcon = new ImageIcon(imageData);
    int width = imageIcon.getIconWidth();
    if (width == maxWidth) {
        return imageData;
    }
    int height = imageIcon.getIconHeight();
    LOG.debug("imageIcon width: " + width + "  height: " + height);
    // If the image is larger than the max width, we need to resize it
    if (maxWidth > 0 && width > maxWidth) {
        // Determine the shrink ratio
        final double ratio = (double) maxWidth / imageIcon.getIconWidth();
        LOG.debug("resize ratio: " + ratio);
        height = (int) (imageIcon.getIconHeight() * ratio);
        width = maxWidth;
        LOG.debug("imageIcon post scale width: " + width + "  height: " + height);
    }
    // Create a new empty image buffer to "draw" the resized image into
    final BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    // Create a Graphics object to do the "drawing"
    final Graphics2D g2d = bufferedImage.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
    // Draw the resized image
    g2d.drawImage(imageIcon.getImage(), 0, 0, width, height, null);
    g2d.dispose();
    // Now our buffered image is ready
    // Encode it as a JPEG
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
    encoder.encode(bufferedImage);
    return baos.toByteArray();
}

From source file:org.squidy.designer.shape.VisualShape.java

@Override
protected final void paint(PPaintContext paintContext) {
    super.paint(paintContext);

    Graphics2D g = paintContext.getGraphics();

    // Set default font.
    g.setFont(internalFont);//  w  w w .j  ava2  s  .c o m

    //      if (!renderingHintsSet) {
    if (isRenderPrimitive()) {
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
        g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
        g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    } else {
        // Use anti aliasing -> May slow down performance.
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DEFAULT);
        g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                RenderingHints.VALUE_FRACTIONALMETRICS_DEFAULT);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    }
    //         renderingHintsSet = true;
    //      }

    // Paint the shapes visual representation.
    paintShape(paintContext);

    // Allows visual debugging if enabled.
    if (DebugConstants.ENABLED) {
        paintDebug(paintContext);
    }
}