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:com.igormaznitsa.mindmap.swing.panel.utils.ScalableIcon.java

public synchronized Image getImage(final double scale) {
    if (Double.compare(this.currentScaleFactor, scale) != 0) {
        this.scaledCachedImage = null;
    }//w ww.  j  a v  a 2  s . c o m

    if (this.scaledCachedImage == null) {
        this.currentScaleFactor = scale;

        final int imgw = this.baseImage.getWidth(null);
        final int imgh = this.baseImage.getHeight(null);
        final int scaledW = (int) Math.round(imgw * this.baseScaleX * scale);
        final int scaledH = (int) Math.round(imgh * this.baseScaleY * scale);

        final BufferedImage img = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_ARGB);
        final Graphics2D g = (Graphics2D) img.getGraphics();

        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);

        g.drawImage(this.baseImage, 0, 0, scaledW, scaledH, null);
        g.dispose();

        this.scaledCachedImage = img;
    }
    return this.scaledCachedImage;
}

From source file:com.bbn.c2s2.pint.testdata.chart.ScatterPlot.java

public ScatterPlot(String chartTitle, String domainAxisTitle, String rangeAxisTitle, double[][] data) {
    super(chartTitle);
    this.data = data;
    final NumberAxis domainAxis = new NumberAxis(domainAxisTitle);
    domainAxis.setAutoRangeIncludesZero(false);
    final NumberAxis rangeAxis = new NumberAxis(rangeAxisTitle);
    rangeAxis.setAutoRangeIncludesZero(false);
    XYDataset dataSet = getDataSet(data);
    XYItemRenderer renderer = getRenderer();
    final XYPlot plot = new XYPlot(dataSet, domainAxis, rangeAxis, renderer);
    //      plot.
    //      final FastScatterPlot plot = new FastScatterPlot(data, domainAxis,
    //            rangeAxis);
    //      DrawingSupplier supplier = new ModifiedDrawingSupplier(5.0);
    //      plot.setDrawingSupplier(supplier);
    chart = new JFreeChart(chartTitle, plot);
    chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    chart.removeLegend();/*  w  w  w .j a  v  a2  s . co m*/

    final ChartPanel panel = new ChartPanel(chart, true);
    panel.setPreferredSize(new java.awt.Dimension(500, 270));
    panel.setMinimumDrawHeight(10);
    panel.setMaximumDrawHeight(2000);
    panel.setMinimumDrawWidth(20);
    panel.setMaximumDrawWidth(2000);

    setContentPane(panel);
}

From source file:org.jcurl.core.swing.WCComponent.java

private BufferedImage renderPng(final String watermark) {
    final BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
    final Graphics2D g2 = (Graphics2D) img.getGraphics();
    {//from  ww w  .  j  av a  2  s .c  om
        final Map<Key, Object> hints = new HashMap<Key, Object>();
        hints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        hints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        hints.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        hints.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        hints.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
        hints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.addRenderingHints(hints);
    }
    final Font f0 = g2.getFont();
    paint(g2);
    g2.setTransform(new AffineTransform());
    if (watermark != null) {
        if (log.isDebugEnabled())
            log.debug(f0);
        g2.setFont(f0);
        g2.setColor(new Color(0, 0, 0, 128));
        g2.drawString(watermark, 10, 20);
    }
    g2.dispose();
    return img;
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.PNGImageExporter.java

public BufferedImage generateImage() throws IOException {
    final int DEFAULT_CELL_WIDTH = 48;
    final int DEFAULT_CELL_HEIGHT = 48;

    final int imgWidth = this.docOptions.getImage() == null ? DEFAULT_CELL_WIDTH * this.docOptions.getColumns()
            : Math.round(this.docOptions.getImage().getSVGWidth());
    final int imgHeight = this.docOptions.getImage() == null ? DEFAULT_CELL_HEIGHT * this.docOptions.getRows()
            : Math.round(this.docOptions.getImage().getSVGHeight());

    final BufferedImage result;
    if (exportData.isBackgroundImageExport() && this.docOptions.getImage() != null) {
        result = this.docOptions.getImage().rasterize(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
    } else {/*  w w w  . j a  va2s  .c  o m*/
        result = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_ARGB);
    }

    final Graphics2D gfx = result.createGraphics();
    gfx.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    gfx.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    final HexEngine<Graphics2D> engine = new HexEngine<Graphics2D>(DEFAULT_CELL_WIDTH, DEFAULT_CELL_HEIGHT,
            this.docOptions.getHexOrientation());

    final List<HexFieldLayer> reversedNormalizedStack = new ArrayList<HexFieldLayer>();
    for (int i = this.exportData.getLayers().size() - 1; i >= 0; i--) {
        final LayerExportRecord rec = this.exportData.getLayers().get(i);
        if (rec.isAllowed()) {
            reversedNormalizedStack.add(rec.getLayer());
        }
    }

    if (Thread.currentThread().isInterrupted())
        return null;

    final HexFieldValue[] stackOfValues = new HexFieldValue[reversedNormalizedStack.size()];

    engine.setModel(new HexEngineModel<HexFieldValue[]>() {

        @Override
        public int getColumnNumber() {
            return docOptions.getColumns();
        }

        @Override
        public int getRowNumber() {
            return docOptions.getRows();
        }

        @Override
        public HexFieldValue[] getValueAt(final int col, final int row) {
            Arrays.fill(stackOfValues, null);

            for (int index = 0; index < reversedNormalizedStack.size(); index++) {
                stackOfValues[index] = reversedNormalizedStack.get(index).getHexValueAtPos(col, row);
            }
            return stackOfValues;
        }

        @Override
        public HexFieldValue[] getValueAt(final HexPosition pos) {
            return this.getValueAt(pos.getColumn(), pos.getRow());
        }

        @Override
        public void setValueAt(int col, int row, HexFieldValue[] value) {
        }

        @Override
        public void setValueAt(HexPosition pos, HexFieldValue[] value) {
        }

        @Override
        public boolean isPositionValid(final int col, final int row) {
            return col >= 0 && col < docOptions.getColumns() && row >= 0 && row < docOptions.getRows();
        }

        @Override
        public boolean isPositionValid(final HexPosition pos) {
            return this.isPositionValid(pos.getColumn(), pos.getRow());
        }

        @Override
        public void attachedToEngine(final HexEngine<?> engine) {
        }

        @Override
        public void detachedFromEngine(final HexEngine<?> engine) {
        }
    });

    final HexRect2D visibleSize = engine.getVisibleSize();
    final float xcoeff = (float) result.getWidth() / visibleSize.getWidth();
    final float ycoeff = (float) result.getHeight() / visibleSize.getHeight();
    engine.setScale(xcoeff, ycoeff);

    final Image[][] cachedIcons = new Image[this.exportData.getLayers().size()][];
    engine.setRenderer(new ColorHexRender() {

        private final Stroke stroke = new BasicStroke(docOptions.getLineWidth());

        @Override
        public Stroke getStroke() {
            return this.stroke;
        }

        @Override
        public Color getFillColor(HexEngineModel<?> model, int col, int row) {
            return null;
        }

        @Override
        public Color getBorderColor(HexEngineModel<?> model, int col, int row) {
            return exportData.isExportHexBorders() ? docOptions.getColor() : null;
        }

        @Override
        public void drawExtra(HexEngine<Graphics2D> engine, Graphics2D g, int col, int row, Color borderColor,
                Color fillColor) {
        }

        @Override
        public void drawUnderBorder(final HexEngine<Graphics2D> engine, final Graphics2D g, final int col,
                final int row, final Color borderColor, final Color fillColor) {
            final HexFieldValue[] stackValues = (HexFieldValue[]) engine.getModel().getValueAt(col, row);
            for (int i = 0; i < stackValues.length; i++) {
                final HexFieldValue valueToDraw = stackValues[i];
                if (valueToDraw == null) {
                    continue;
                }
                g.drawImage(cachedIcons[i][valueToDraw.getIndex()], 0, 0, null);
            }
        }

    });

    final Path2D hexShape = ((ColorHexRender) engine.getRenderer()).getHexPath();
    final int cellWidth = hexShape.getBounds().width;
    final int cellHeight = hexShape.getBounds().height;

    for (int layerIndex = 0; layerIndex < reversedNormalizedStack.size()
            && !Thread.currentThread().isInterrupted(); layerIndex++) {
        final HexFieldLayer theLayer = reversedNormalizedStack.get(layerIndex);
        final Image[] cacheLineForLayer = new Image[theLayer.getHexValuesNumber()];
        for (int valueIndex = 1; valueIndex < theLayer.getHexValuesNumber(); valueIndex++) {
            cacheLineForLayer[valueIndex] = theLayer.getHexValueForIndex(valueIndex).makeIcon(cellWidth,
                    cellHeight, hexShape, true);
        }
        cachedIcons[layerIndex] = cacheLineForLayer;
    }

    engine.drawWithThreadInterruptionCheck(gfx);
    if (Thread.currentThread().isInterrupted())
        return null;

    if (this.exportData.isCellCommentariesExport()) {
        final Iterator<Entry<HexPosition, String>> iterator = this.cellComments.iterator();
        gfx.setFont(new Font("Arial", Font.BOLD, 12));
        while (iterator.hasNext() && !Thread.currentThread().isInterrupted()) {
            final Entry<HexPosition, String> item = iterator.next();
            final HexPosition pos = item.getKey();
            final String text = item.getValue();
            final float x = engine.calculateX(pos.getColumn(), pos.getRow());
            final float y = engine.calculateY(pos.getColumn(), pos.getRow());

            final Rectangle2D textBounds = gfx.getFontMetrics().getStringBounds(text, gfx);

            final float dx = x - ((float) textBounds.getWidth() - engine.getCellWidth()) / 2;

            gfx.setColor(Color.BLACK);
            gfx.drawString(text, dx, y);
            gfx.setColor(Color.WHITE);
            gfx.drawString(text, dx - 2, y - 2);
        }
    }

    gfx.dispose();

    return result;
}

From source file:com.igormaznitsa.jhexed.values.HexSVGImageValue.java

@Override
public BufferedImage makeIcon(final int width, final int height, final Path2D shape, final boolean allowAlpha) {
    try {//from   w w w.  j a va2  s  .  c  o  m
        final BufferedImage img = this.image.rasterize(width, height, BufferedImage.TYPE_INT_ARGB);
        if (shape == null) {
            return img;
        } else {
            final BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            final Graphics2D g = result.createGraphics();
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                    RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
            g.setClip(makeTransformedPathForSize(width, height, shape));
            g.drawImage(img, 0, 0, null);
            g.dispose();
            return result;
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:peakml.util.swt.widget.IntensityTrendGraph.java

public BufferedImage getGraphImage(int width, int height) {
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = img.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    linechart.draw(g, new Rectangle(0, 0, width, height));

    return img;//  www .  j  a  v a 2s .co  m
}

From source file:forge.view.arcane.util.OutlinedLabel.java

/** {@inheritDoc} */
@Override/*from  w  ww. j  a  v  a  2  s.c  om*/
public final void paint(final Graphics g) {
    if (getText().length() == 0) {
        return;
    }

    Dimension size = getSize();
    //
    //        if( size.width < 50 ) {
    //            g.setColor(Color.cyan);
    //            g.drawRect(0, 0, size.width-1, size.height-1);
    //        }

    Graphics2D g2d = (Graphics2D) g;

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    int textX = outlineSize, textY = 0;
    int wrapWidth = Math.max(0, wrap ? size.width - outlineSize * 2 : Integer.MAX_VALUE);

    final String text = getText();
    AttributedString attributedString = new AttributedString(text);
    if (!StringUtils.isEmpty(text)) {
        attributedString.addAttribute(TextAttribute.FONT, getFont());
    }
    AttributedCharacterIterator charIterator = attributedString.getIterator();
    FontRenderContext fontContext = g2d.getFontRenderContext();

    LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator,
            BreakIterator.getWordInstance(Locale.ENGLISH), fontContext);
    int lineCount = 0;
    while (measurer.getPosition() < charIterator.getEndIndex()) {
        measurer.nextLayout(wrapWidth);
        lineCount++;
        if (lineCount > 2) {
            break;
        }
    }
    charIterator.first();
    // Use char wrap if word wrap would cause more than two lines of text.
    if (lineCount > 2) {
        measurer = new LineBreakMeasurer(charIterator, BreakIterator.getCharacterInstance(Locale.ENGLISH),
                fontContext);
    } else {
        measurer.setPosition(0);
    }
    while (measurer.getPosition() < charIterator.getEndIndex()) {
        TextLayout textLayout = measurer.nextLayout(wrapWidth);
        float ascent = textLayout.getAscent();
        textY += ascent; // Move down to baseline.

        g2d.setColor(outlineColor);
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.8f));

        textLayout.draw(g2d, textX + outlineSize, textY - outlineSize);
        textLayout.draw(g2d, textX + outlineSize, textY + outlineSize);
        textLayout.draw(g2d, textX - outlineSize, textY - outlineSize);
        textLayout.draw(g2d, textX - outlineSize, textY + outlineSize);

        g2d.setColor(getForeground());
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
        textLayout.draw(g2d, textX, textY);

        // Move down to top of next line.
        textY += textLayout.getDescent() + textLayout.getLeading();
    }
}

From source file:savant.view.tracks.ContinuousTrackRenderer.java

@Override
public void render(Graphics2D g2, GraphPaneAdapter gp) throws RenderingException {

    renderPreCheck();// w ww. j  a v a  2  s . c  o  m

    AxisRange axisRange = (AxisRange) instructions.get(DrawingInstruction.AXIS_RANGE);
    gp.setXRange(axisRange.getXRange());
    gp.setYRange(axisRange.getYRange());

    if (gp.needsToResize())
        return;

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

    ColourScheme cs = (ColourScheme) instructions.get(DrawingInstruction.COLOUR_SCHEME);
    Color fillcolor = cs.getColor(ColourKey.CONTINUOUS_FILL);
    Color linecolor = cs.getColor(ColourKey.CONTINUOUS_LINE);

    GeneralPath path = new GeneralPath();
    double xFormXPos = Double.NaN, xFormYPos = Double.NaN;

    double yPixel0 = gp.transformYPos(0.0);
    LOG.debug("h=" + gp.getHeight() + ", yMin=" + gp.getYRange().getFrom() + ", unitHeight="
            + gp.getUnitHeight() + " \u27A4 yPixel0=" + yPixel0);

    double maxData = 0;
    boolean haveOpenPath = false;
    boolean haveData = false;
    if (data != null) {
        for (int i = 0; i < data.size(); i++) {
            ContinuousRecord continuousRecord = (ContinuousRecord) data.get(i);
            int xPos = continuousRecord.getPosition();
            float yPos = continuousRecord.getValue();
            if (Float.isNaN(yPos)) {
                // Hit a position with no data.  May need to close off the current path.
                if (haveOpenPath) {
                    path.lineTo(xFormXPos, yPixel0);
                    path.closePath();
                    haveOpenPath = false;
                }
            } else {
                haveData = true;
                xFormXPos = gp.transformXPos(xPos);//+gp.getUnitWidth()/2;
                xFormYPos = gp.transformYPos(yPos);
                if (!haveOpenPath) {
                    // Start our path off with a vertical line.
                    path.moveTo(xFormXPos, yPixel0);
                    haveOpenPath = true;
                }
                path.lineTo(xFormXPos, xFormYPos);
                Rectangle2D rec = new Rectangle2D.Double(
                        xFormXPos - ((xFormXPos - path.getCurrentPoint().getX()) / 2), 0,
                        Math.max(xFormXPos - path.getCurrentPoint().getX(), 1), gp.getHeight());
                recordToShapeMap.put(continuousRecord, rec);
                xFormXPos = gp.transformXPos(xPos + 1);
                path.lineTo(xFormXPos, xFormYPos);
            }
            if (yPos > maxData) {
                maxData = yPos;
            }
        }
    }
    if (!haveData) {
        throw new RenderingException("No data in range", RenderingException.INFO_PRIORITY);
    }
    if (haveOpenPath) {
        // Path needs to be closed.
        path.lineTo(xFormXPos, yPixel0);
        path.closePath();
    }

    g2.setColor(fillcolor);
    g2.fill(path);
    g2.setColor(linecolor);
    g2.draw(path);

    if (axisRange.getYRange().getFrom() < 0) {
        g2.setColor(Color.darkGray);
        g2.draw(new Line2D.Double(0.0, yPixel0, gp.getWidth(), yPixel0));
    }
}

From source file:kz.supershiny.core.services.ImageService.java

/**
 * Creates thumb for image.// ww  w .  j av  a  2s  .  c  o  m
 *
 * @param originalData original image in byte array
 * @param type original - 0, large - 1, small - 2
 * @return resized image in byte array
 */
public static byte[] resizeImage(byte[] originalData, ImageSize type) {
    //if original flag, then return original
    if (type.equals(ImageSize.ORIGINAL)) {
        return originalData;
    }

    BufferedImage originalImage = null;
    BufferedImage resizedImage = null;
    byte[] result = null;
    //convert bytes to BufferedImage
    try (InputStream in = new ByteArrayInputStream(originalData)) {
        originalImage = ImageIO.read(in);
    } catch (IOException ex) {
        LOG.error("Cannot convert byte array to BufferedImage!", ex);
        return null;
    }
    //get original size
    int scaledHeight = originalImage.getHeight();
    int scaledWidth = originalImage.getWidth();

    switch (type) {
    case LARGE:
        scaledWidth = LARGE_WIDTH;
        scaledHeight = LARGE_HEIGHT;
        break;
    case SMALL:
        scaledWidth = SMALL_WIDTH;
        scaledHeight = SMALL_HEIGHT;
        break;
    default:
        break;
    }
    //calculate aspect ratio
    float ratio = 1.0F * originalImage.getWidth() / originalImage.getHeight();
    if (ratio > 1.0F) {
        scaledHeight = (int) (scaledHeight / ratio);
    } else {
        scaledWidth = (int) (scaledWidth * ratio);
    }
    //resize with hints
    resizedImage = new BufferedImage(scaledWidth, scaledHeight,
            originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType());

    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
    g.dispose();
    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);
    //convert BufferedImage to bytes
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ImageIO.write(resizedImage, "png", baos);
        baos.flush();
        result = baos.toByteArray();
    } catch (IOException ex) {
        LOG.error("Cannot convert BufferedImage to byte array!", ex);
    }
    return result;
}

From source file:org.shredzone.commons.captcha.impl.DefaultCaptchaGenerator.java

@Override
public BufferedImage createCaptcha(char[] text) {
    if (text == null || text.length == 0) {
        throw new IllegalArgumentException("No captcha text given");
    }/*from  w w w  .  jav a 2 s  . c o m*/

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = image.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setBackground(Color.WHITE);
    g2d.setColor(Color.BLACK);

    clearCanvas(g2d);

    if (showGrid) {
        drawGrid(g2d);
    }

    int charMaxWidth = width / text.length;
    int xPos = 0;
    for (char ch : text) {
        drawCharacter(g2d, ch, xPos, charMaxWidth);
        xPos += charMaxWidth;
    }

    g2d.dispose();
    return image;
}