Example usage for java.awt Graphics2D setColor

List of usage examples for java.awt Graphics2D setColor

Introduction

In this page you can find the example usage for java.awt Graphics2D setColor.

Prototype

public abstract void setColor(Color c);

Source Link

Document

Sets this graphics context's current color to the specified color.

Usage

From source file:edu.umn.cs.spatialHadoop.operations.GeometricPlot.java

private static <S extends Shape> void plotLocal(Path inFile, Path outFile, OperationsParams params)
        throws IOException {
    int width = params.getInt("width", 1000);
    int height = params.getInt("height", 1000);

    Color strokeColor = params.getColor("color", Color.BLACK);
    int color = strokeColor.getRGB();

    String hdfDataset = (String) params.get("dataset");
    Shape shape = hdfDataset != null ? new NASARectangle() : (Shape) params.getShape("shape", null);
    Shape plotRange = params.getShape("rect", null);

    boolean keepAspectRatio = params.is("keep-ratio", true);

    String valueRangeStr = (String) params.get("valuerange");
    MinMax valueRange;//from   ww w .  ja  v a2  s.co  m
    if (valueRangeStr == null) {
        valueRange = null;
    } else {
        String[] parts = valueRangeStr.split(",");
        valueRange = new MinMax(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
    }

    InputSplit[] splits;
    FileSystem inFs = inFile.getFileSystem(params);
    FileStatus inFStatus = inFs.getFileStatus(inFile);
    if (inFStatus != null && !inFStatus.isDir()) {
        // One file, retrieve it immediately.
        // This is useful if the input is a hidden file which is automatically
        // skipped by FileInputFormat. We need to plot a hidden file for the case
        // of plotting partition boundaries of a spatial index
        splits = new InputSplit[] { new FileSplit(inFile, 0, inFStatus.getLen(), new String[0]) };
    } else {
        JobConf job = new JobConf(params);
        ShapeInputFormat<Shape> inputFormat = new ShapeInputFormat<Shape>();
        ShapeInputFormat.addInputPath(job, inFile);
        splits = inputFormat.getSplits(job, 1);
    }

    boolean vflip = params.is("vflip");

    Rectangle fileMbr;
    if (plotRange != null) {
        fileMbr = plotRange.getMBR();
    } else if (hdfDataset != null) {
        // Plotting a NASA file
        fileMbr = new Rectangle(-180, -90, 180, 90);
    } else {
        fileMbr = FileMBR.fileMBR(inFile, params);
    }

    if (keepAspectRatio) {
        // Adjust width and height to maintain aspect ratio
        if (fileMbr.getWidth() / fileMbr.getHeight() > (double) width / height) {
            // Fix width and change height
            height = (int) (fileMbr.getHeight() * width / fileMbr.getWidth());
        } else {
            width = (int) (fileMbr.getWidth() * height / fileMbr.getHeight());
        }
    }

    boolean adaptiveSample = shape instanceof Point && params.getBoolean("sample", false);
    float adaptiveSampleRatio = 0.0f;
    if (adaptiveSample) {
        // Calculate the sample ratio
        long recordCount = FileMBR.fileMBR(inFile, params).recordCount;
        adaptiveSampleRatio = params.getFloat(AdaptiveSampleFactor, 1.0f) * width * height / recordCount;
    }

    boolean gradualFade = !(shape instanceof Point) && params.getBoolean("fade", false);

    if (hdfDataset != null) {
        // Collects some stats about the HDF file
        if (valueRange == null)
            valueRange = Aggregate.aggregate(new Path[] { inFile }, params);
        NASAPoint.minValue = valueRange.minValue;
        NASAPoint.maxValue = valueRange.maxValue;
        NASAPoint.setColor1(params.getColor("color1", Color.BLUE));
        NASAPoint.setColor2(params.getColor("color2", Color.RED));
        NASAPoint.gradientType = params.getGradientType("gradient", NASAPoint.GradientType.GT_HUE);
    }

    double scale2 = (double) width * height / (fileMbr.getWidth() * fileMbr.getHeight());
    double scale = Math.sqrt(scale2);

    // Create an image
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    Color bg_color = params.getColor("bgcolor", new Color(0, 0, 0, 0));
    graphics.setBackground(bg_color);
    graphics.clearRect(0, 0, width, height);
    graphics.setColor(strokeColor);

    for (InputSplit split : splits) {
        if (hdfDataset != null) {
            // Read points from the HDF file
            RecordReader<NASADataset, NASAShape> reader = new HDFRecordReader(params, (FileSplit) split,
                    hdfDataset, true);
            NASADataset dataset = reader.createKey();

            while (reader.next(dataset, (NASAShape) shape)) {
                // Skip with a fixed ratio if adaptive sample is set
                if (adaptiveSample && Math.random() > adaptiveSampleRatio)
                    continue;
                if (plotRange == null || shape.isIntersected(shape)) {
                    shape.draw(graphics, fileMbr, width, height, 0.0);
                }
            }
            reader.close();
        } else {
            RecordReader<Rectangle, Shape> reader = new ShapeRecordReader<Shape>(params, (FileSplit) split);
            Rectangle cell = reader.createKey();
            while (reader.next(cell, shape)) {
                // Skip with a fixed ratio if adaptive sample is set
                if (adaptiveSample && Math.random() > adaptiveSampleRatio)
                    continue;
                Rectangle shapeMBR = shape.getMBR();
                if (shapeMBR != null) {
                    if (plotRange == null || shapeMBR.isIntersected(plotRange)) {
                        if (gradualFade) {
                            double sizeInPixels = (shapeMBR.getWidth() + shapeMBR.getHeight()) * scale;
                            if (sizeInPixels < 1.0 && Math.round(sizeInPixels * 255) < 1.0) {
                                // This shape can be safely skipped as it is too small to be plotted
                                continue;
                            } else {
                                int alpha = (int) Math.round(sizeInPixels * 255);
                                graphics.setColor(new Color((alpha << 24) | color, true));
                            }
                        }
                        shape.draw(graphics, fileMbr, width, height, scale2);
                    }
                }
            }
            reader.close();
        }
    }
    // Write image to output
    graphics.dispose();
    if (vflip) {
        AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
        tx.translate(0, -image.getHeight());
        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
        image = op.filter(image, null);
    }
    FileSystem outFs = outFile.getFileSystem(params);
    OutputStream out = outFs.create(outFile, true);
    ImageIO.write(image, "png", out);
    out.close();

}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private String generaImagenCombustible(double porcentaje) {
    try {/*from   w  w  w . j av a 2s  .  c om*/
        int width = 186 * 3;
        int height = 15 * 3;
        IndicadorBarraGraphicsView view = new IndicadorBarraGraphicsView();
        view.setWidthBar(width);
        view.setHeightBar(height);
        view.setPorcentaje(porcentaje);
        BufferedImage off_Image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = off_Image.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, width, height);
        view.paint(g2);
        File file = new File("data/nivelCombustible.jpg");
        saveJPG(off_Image, file);
        return file.getCanonicalPath();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:fr.ign.cogit.geoxygene.appli.layer.LayerViewAwtPanel.java

public void saveAsImage(String fileName, int width, int height, boolean doSaveWorldFile, boolean drawOverlay) {
    Color bg = this.getBackground();
    BufferedImage outImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = outImage.createGraphics();
    // TEMP/* w  ww  . j a  va 2 s.c  o m*/
    graphics.setColor(bg);
    graphics.fillRect(0, 0, width, height);
    int tmpw = this.getWidth();
    int tmph = this.getHeight();
    // We save the old extent to force the Viewport to keep the old
    // window in world coordinates.
    IEnvelope env = this.getViewport().getEnvelopeInModelCoordinates();
    // Artificially resize the canvas to the image dimensions.
    this.setSize(width, height);
    try {
        // We zoom to the old extent in the resized canvas.
        this.getViewport().zoom(env);
    } catch (NoninvertibleTransformException e2) {
        logger.error("In Image Export : failed to zoom in the correct extent.");
        e2.printStackTrace();
    }
    this.renderingManager.renderAll();
    long time = System.currentTimeMillis();
    long twaited = 0;
    while (this.renderingManager.isRendering() && twaited < 15000) {
        // Wait for the rendering to end for a maximum of 15s. If the
        // rendering is not finished after this delay,
        // we give up.
        twaited = System.currentTimeMillis() - time;
    }
    if (this.renderingManager.isRendering()) {
        logger.error("Export to image : waited 15s but the rendering is still not finished. Abort.");
        return;
    }

    // We have to impose a bbox !!!
    this.getRenderingManager().copyTo(graphics);

    if (drawOverlay)
        this.paintOverlays(graphics);
    graphics.dispose();
    try {
        ImgUtil.saveImage(outImage, fileName);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    if (doSaveWorldFile) {
        String wld = FilenameUtils.removeExtension(fileName) + ".wld";
        try {
            AffineTransform t = this.getViewport().getModelToViewTransform();
            fr.ign.cogit.geoxygene.util.conversion.WorldFileWriter.write(new File(wld), t.getScaleX(),
                    t.getScaleY(), this.getViewport().getViewOrigin().getX(),
                    this.getViewport().getViewOrigin().getY(), this.getHeight());
        } catch (NoninvertibleTransformException e) {
            logger.error("Failed to save the world file associated with the image file " + fileName);
            e.printStackTrace();
        }
    }

    // Finally, rollback the canvas to its original size.
    this.setSize(tmpw, tmph);
    try {
        // Zoom back to the "normal" extent
        this.getViewport().zoom(env);
    } catch (NoninvertibleTransformException e2) {
        logger.error("In Image Export : failed to zoom back to the original LayerViewPanel extent.");
        e2.printStackTrace();
        return;
    }
}

From source file:edu.ku.brc.specify.utilapps.ERDTable.java

/**
 * Returns the BufferedImage of a background shadow. I creates a large rectangle than the orignal image.
 * @return Returns the BufferedImage of a background shadow. I creates a large rectangle than the orignal image.
 *//*from  ww  w .  j av  a  2 s. c o m*/
private BufferedImage getBackgroundImageBuffer() {
    if (shadowBuffer == null) {
        ShadowFactory factory = new ShadowFactory(SHADOW_SIZE, 0.17f, Color.BLACK);

        Dimension size = inner.getSize();
        BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2 = image.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, image.getWidth(), image.getHeight());
        g2.dispose();

        shadowBuffer = factory.createShadow(image);
    }
    return shadowBuffer;
}

From source file:edworld.pdfreader4humans.PDFReader.java

public BufferedImage createPageImage(int pageNumber, int scaling, Color inkColor, Color backgroundColor,
        boolean showStructure) throws IOException {
    Map<String, Font> fonts = new HashMap<String, Font>();
    PDRectangle cropBox = getPageCropBox(pageNumber);
    BufferedImage image = new BufferedImage(Math.round(cropBox.getWidth() * scaling),
            Math.round(cropBox.getHeight() * scaling), BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setBackground(backgroundColor);
    graphics.clearRect(0, 0, image.getWidth(), image.getHeight());
    graphics.setColor(backgroundColor);
    graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
    graphics.setColor(inkColor);/* ww  w .  j  a va  2  s  .  c o  m*/
    graphics.scale(scaling, scaling);
    for (Component component : getFirstLevelComponents(pageNumber))
        draw(component, graphics, inkColor, backgroundColor, showStructure, fonts);
    graphics.dispose();
    return image;
}

From source file:com.nbt.TileCanvas.java

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

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

    g2d.setColor(Color.BLACK);
    int x = 0, y = 0;
    Dimension size = getSize();/*www  .  j  a  v a  2s  . com*/
    g2d.fillRect(x, y, size.width, size.height);

    final int altitude = getAltitude();
    for (int w = 0; w < getTileWidth(); w++) {
        x = w * SPRITE_SIZE;
        for (int h = 0; h < getTileHeight(); h++) {
            y = h * SPRITE_SIZE;

            int xOffset = w + getTileX();
            int zOffset = h + getTileZ();
            BufferedImage tile = getBackgroundTile(xOffset, altitude, zOffset);
            if (tile != null)
                g2d.drawImage(tile, x, y, null);
        }
    }

    g2d.dispose();
}

From source file:org.nekorp.workflow.desktop.servicio.reporte.orden.servicio.OrdenServicioDataFactory.java

private void generaImagenDamage(ShapeView fondo, List<DamageDetailsVB> danios, File outputfile, int width,
        int height) {
    try {/*from ww  w. j  a  va 2s .  co m*/
        Point contexto = new Point((width - fondo.getShapeWidth()) / 2, (height - fondo.getShapeHeight()) / 2);
        BufferedImage off_Image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = off_Image.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, width, height);
        AffineTransform saveXform = g2.getTransform();
        AffineTransform toCenterAt = new AffineTransform();
        toCenterAt.translate(contexto.getX(), contexto.getY());
        g2.transform(toCenterAt);
        fondo.paint(g2);
        g2.setTransform(saveXform);
        for (DamageDetailsVB x : danios) {
            DamageDetailGraphicsView obj = new DamageDetailGraphicsView();
            obj.setPosicion(new Point(x.getX(), x.getY()));
            obj.setContexto(contexto);
            if (x.getX() <= fondo.getShapeWidth() / 2) {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorIzquierda);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorIzquierda);
                }
            } else {
                if (x.getY() <= fondo.getShapeHeight() / 2) {
                    obj.setOrientacion(DamageDetailGraphicsView.SuperiorDerecha);
                } else {
                    obj.setOrientacion(DamageDetailGraphicsView.InferiorDerecha);
                }
            }
            obj.setCategoria(x.getCategoria());
            obj.setCaracteristica(x.getCaracteristica());
            obj.paint(g2);
        }
        saveJPG(off_Image, outputfile);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.piketec.jenkins.plugins.tpt.publisher.PieChart.java

/**
 * Render the pie chart with the given height
 * /*from   w ww  .j  a  v  a  2 s  .c o  m*/
 * @param height
 *          The height of the resulting image
 * @return The pie chart rendered as an image
 */
public BufferedImage render(int height) {
    BufferedImage image = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.scale(zoom, zoom);
    // fill background to white
    g2.setColor(Color.WHITE);
    g2.fill(new Rectangle(totalWidth, totalHeight));
    // prepare render hints
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setStroke(new BasicStroke(4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));

    // draw shadow image
    g2.drawImage(pieShadow.getImage(), 0, 0, pieShadow.getImageObserver());

    double start = 0;
    List<Arc2D> pies = new ArrayList<>();
    // pie segmente erzeugen und fuellen
    if (total == 0) {
        g2.setColor(BRIGHT_GRAY);
        g2.fillOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
        g2.setColor(Color.WHITE);
        g2.drawOval(centerX - radius, centerY - radius, 2 * radius, 2 * radius);
    } else {
        for (Segment s : segments) {
            double portionDegrees = s.getPortion() / total;
            Arc2D pie = paintPieSegment(g2, start, portionDegrees, s.getColor());
            if (withSubSegments) {
                double smallRadius = radius * s.getSubSegmentRatio();
                paintPieSegment(g2, start, portionDegrees, smallRadius, s.getColor().darker());
            }
            start += portionDegrees;
            // portion degree jetzt noch als String (z.B. "17.3%" oder "20%" zusammenbauen)
            String p = String.format(Locale.ENGLISH, "%.1f", Math.rint(portionDegrees * 1000) / 10.0);
            p = removeSuffix(p, ".0"); // evtl. ".0" bei z.B. "25.0" abschneiden (-> "25")
            s.setPercent(p + "%");
            pies.add(pie);
        }
        // weissen Rahmen um die pie segmente zeichen
        g2.setColor(Color.WHITE);
        for (Arc2D pie : pies) {
            g2.draw(pie);
        }
    }
    // Legende zeichnen
    renderLegend(g2);
    // "xx%" Label direkt auf die pie segmente zeichen
    g2.setColor(Color.WHITE);
    float fontSize = 32f;
    g2.setFont(NORMALFONT.deriveFont(fontSize).deriveFont(Font.BOLD));
    start = 0;
    for (Segment s : segments) {
        if (s.getPortion() < 1E-6) {
            continue; // ignore segments with portions that are extremely small
        }
        double portionDegrees = s.getPortion() / total;
        double angle = start + portionDegrees / 2; // genau in der Mitte des Segments
        double xOffsetForCenteredTxt = 8 * s.getPercent().length(); // assume roughly 8px per char
        int x = (int) (centerX + 0.6 * radius * Math.sin(2 * Math.PI * angle) - xOffsetForCenteredTxt);
        int y = (int) (centerY - 0.6 * radius * Math.cos(2 * Math.PI * angle) + fontSize / 2);
        g2.drawString(s.getPercent(), x, y);
        start += portionDegrees;
    }
    return image;
}

From source file:ShapeMover.java

public void update(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    Dimension dim = getSize();/*  w w w.ja v  a 2 s .co  m*/
    int w = (int) dim.getWidth();
    int h = (int) dim.getHeight();
    g2.setStroke(new BasicStroke(8.0f));

    if (isFirstTime) {
        area = new Rectangle(dim);
        rect.setLocation(w / 2 - 50, h / 2 - 25);
        isFirstTime = false;
    }

    // Clears the rectangle that was previously drawn.
    g2.setPaint(Color.white);
    g2.fillRect(0, 0, w, h);

    g2.setColor(Color.red);
    g2.draw(rect);
    g2.setColor(Color.black);
    g2.fill(rect);
}

From source file:algorithm.QRCodeWatermarking.java

/**
 * Creates a PNG image that contains the QR-code with the information from
 * the payload file. The image has the same name as the payload file.
 * //from  w w w  .j  a  v  a  2s  . co m
 * @param payload
 * @return qr code as png image file
 * @throws IOException
 */
private File createBarcodeFile(File payload, String imageFormat, String usedMethod) throws IOException {
    // Create restoration metadata only for the payload file to spare space.
    PayloadSegment metadata = new PayloadSegment(payload);
    metadata.addOptionalProperty("usedMethod", usedMethod);
    byte[] payloadSegment = metadata.getPayloadSegmentBytes();
    String barcodeInformation = new String(payloadSegment);
    int size = getQRCodeSize();
    String outputFileName = FilenameUtils.removeExtension(getOutputFileName(payload)) + "." + imageFormat;
    File outputFile = new File(outputFileName);
    Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
    hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
    BitMatrix byteMatrix = encodeWithQRCode(barcodeInformation, hintMap, size);
    if (byteMatrix == null) {
        return null;
    }
    BufferedImage image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
    image.createGraphics();
    Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, size, size);
    graphics.setColor(Color.BLACK);
    for (int x = 0; x < size; x++) {
        for (int y = 0; y < size; y++) {
            if (byteMatrix.get(x, y)) {
                graphics.fillRect(x, y, 1, 1);
            }
        }
    }
    ImageIO.write(image, imageFormat, outputFile);
    return outputFile;
}