Example usage for java.awt Graphics2D scale

List of usage examples for java.awt Graphics2D scale

Introduction

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

Prototype

public abstract void scale(double sx, double sy);

Source Link

Document

Concatenates the current Graphics2D Transform with a scaling transformation Subsequent rendering is resized according to the specified scaling factors relative to the previous scaling.

Usage

From source file:jhplot.gui.GHPanel.java

/**
 * Print the canvas/*from   w ww.j  av a2  s  .  c o  m*/
 * 
 */
public void printGraph() {

    if (isBorderShown())
        showBorders(false);
    CanvasPanel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    Thread t = new Thread() {
        public void run() {
            try {
                PrinterJob prnJob = PrinterJob.getPrinterJob();
                // set the Printable to the PrinterJob
                prnJob.setPrintable(new Printable() {
                    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) {
                        if (pageIndex == 0) {
                            Graphics2D g2d = (Graphics2D) graphics;
                            double ratioX = pageFormat.getImageableWidth() / CanvasPanel.getSize().width;
                            double ratioY = pageFormat.getImageableHeight() / CanvasPanel.getSize().height;
                            double factor = Math.min(ratioX, ratioY);
                            g2d.scale(factor, factor);
                            g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
                            disableDoubleBuffering(CanvasPanel);
                            CanvasPanel.print(g2d);
                            enableDoubleBuffering(CanvasPanel);
                            return Printable.PAGE_EXISTS;
                        }
                        return Printable.NO_SUCH_PAGE;
                    }
                });

                if (prnJob.printDialog()) {
                    JHPlot.showStatusBarText("Printing..");
                    prnJob.print();
                }
            } catch (PrinterException e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
    CanvasPanel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}

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

/**
 *
 *//*  w w  w. j  a  v  a2s  . c  o m*/
@Override
public void scaleGraphicsContext(Graphics2D g2) throws IllegalArgumentException {
    if (currentScaleFactor > 0.0f) {
        g2.scale(currentScaleFactor, currentScaleFactor);
        g2.translate(currentTranslationX, currentTranslationY);
    } else {
        throw new IllegalArgumentException("An attempt was made to scale with a height or width value of 0");
    }
}

From source file:MyJava3D.java

public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
    if (pi >= 1) {
        return Printable.NO_SUCH_PAGE;
    }/*  w  w w .  j  av  a2 s .com*/

    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    g2d.translate(pf.getImageableWidth() / 2, pf.getImageableHeight() / 2);

    Dimension d = getSize();

    double scale = Math.min(pf.getImageableWidth() / d.width, pf.getImageableHeight() / d.height);
    if (scale < 1.0) {
        g2d.scale(scale, scale);
    }

    g2d.translate(-d.width / 2.0, -d.height / 2.0);

    if (bimg == null) {
        Graphics2D g2 = createGraphics2D(d.width, d.height, null, g2d);
        render(d.width, d.height, g2);
        g2.dispose();
    } else {
        g2d.drawImage(bimg, 0, 0, this);
    }

    return Printable.PAGE_EXISTS;
}

From source file:net.sf.jasperreports.engine.export.JExcelApiMetadataExporter.java

public void exportImage(JRPrintImage element) throws JRException {

    String currentColumnName = element.getPropertiesMap()
            .getProperty(JRXlsAbstractMetadataExporterParameter.PROPERTY_COLUMN_NAME);
    if (currentColumnName != null && currentColumnName.length() > 0) {
        boolean repeatValue = getPropertiesUtil().getBooleanProperty(element,
                JRXlsAbstractMetadataExporterParameter.PROPERTY_REPEAT_VALUE, false);

        setColumnName(currentColumnName);
        setColumnWidth(columnNamesMap.get(currentColumnName), element.getWidth());
        setRowHeight(rowIndex, element.getHeight());

        int topPadding = Math.max(element.getLineBox().getTopPadding().intValue(),
                getImageBorderCorrection(element.getLineBox().getTopPen()));
        int leftPadding = Math.max(element.getLineBox().getLeftPadding().intValue(),
                getImageBorderCorrection(element.getLineBox().getLeftPen()));
        int bottomPadding = Math.max(element.getLineBox().getBottomPadding().intValue(),
                getImageBorderCorrection(element.getLineBox().getBottomPen()));
        int rightPadding = Math.max(element.getLineBox().getRightPadding().intValue(),
                getImageBorderCorrection(element.getLineBox().getRightPen()));

        int availableImageWidth = element.getWidth() - leftPadding - rightPadding;
        availableImageWidth = availableImageWidth < 0 ? 0 : availableImageWidth;

        int availableImageHeight = element.getHeight() - topPadding - bottomPadding;
        availableImageHeight = availableImageHeight < 0 ? 0 : availableImageHeight;

        Renderable renderer = element.getRenderable();

        if (renderer != null && availableImageWidth > 0 && availableImageHeight > 0) {
            if (renderer.getTypeValue() == RenderableTypeEnum.IMAGE) {
                // Image renderers are all asked for their image data and dimension at some point. 
                // Better to test and replace the renderer now, in case of lazy load error.
                renderer = RenderableUtil.getInstance(jasperReportsContext)
                        .getOnErrorRendererForImageData(renderer, element.getOnErrorTypeValue());
                if (renderer != null) {
                    renderer = RenderableUtil.getInstance(jasperReportsContext)
                            .getOnErrorRendererForDimension(renderer, element.getOnErrorTypeValue());
                }/*from w  w w. j  a  va 2s.co  m*/
            } else {
                renderer = new JRWrappingSvgRenderer(renderer,
                        new Dimension(element.getWidth(), element.getHeight()),
                        ModeEnum.OPAQUE == element.getModeValue() ? element.getBackcolor() : null);
            }
        } else {
            renderer = null;
        }

        if (renderer != null) {
            int normalWidth = availableImageWidth;
            int normalHeight = availableImageHeight;

            Dimension2D dimension = renderer.getDimension(jasperReportsContext);
            if (dimension != null) {
                normalWidth = (int) dimension.getWidth();
                normalHeight = (int) dimension.getHeight();
            }

            float xalignFactor = 0f;
            switch (element.getHorizontalAlignmentValue()) {
            case RIGHT: {
                xalignFactor = 1f;
                break;
            }
            case CENTER: {
                xalignFactor = 0.5f;
                break;
            }
            case LEFT:
            default: {
                xalignFactor = 0f;
                break;
            }
            }

            float yalignFactor = 0f;
            switch (element.getVerticalAlignmentValue()) {
            case BOTTOM: {
                yalignFactor = 1f;
                break;
            }
            case MIDDLE: {
                yalignFactor = 0.5f;
                break;
            }
            case TOP:
            default: {
                yalignFactor = 0f;
                break;
            }
            }

            byte[] imageData = null;

            switch (element.getScaleImageValue()) {
            case CLIP: {
                int dpi = getPropertiesUtil().getIntegerProperty(Renderable.PROPERTY_IMAGE_DPI, 72);
                double scale = dpi / 72d;

                BufferedImage bi = new BufferedImage((int) (scale * availableImageWidth),
                        (int) (scale * availableImageHeight), BufferedImage.TYPE_INT_ARGB);

                Graphics2D grx = bi.createGraphics();
                grx.scale(scale, scale);
                grx.clip(new Rectangle(0, 0, availableImageWidth, availableImageHeight));

                renderer.render(jasperReportsContext, grx,
                        new Rectangle((int) (xalignFactor * (availableImageWidth - normalWidth)),
                                (int) (yalignFactor * (availableImageHeight - normalHeight)), normalWidth,
                                normalHeight));

                imageData = JRImageLoader.getInstance(jasperReportsContext).loadBytesFromAwtImage(bi,
                        ImageTypeEnum.PNG);

                break;
            }
            case FILL_FRAME: {
                imageData = renderer.getImageData(jasperReportsContext);

                break;
            }
            case RETAIN_SHAPE:
            default: {
                if (element.getHeight() > 0) {
                    double ratio = (double) normalWidth / (double) normalHeight;

                    if (ratio > (double) availableImageWidth / (double) availableImageHeight) {
                        normalWidth = availableImageWidth;
                        normalHeight = (int) (availableImageWidth / ratio);
                    } else {
                        normalWidth = (int) (availableImageHeight * ratio);
                        normalHeight = availableImageHeight;
                    }

                    imageData = renderer.getImageData(jasperReportsContext);
                }

                break;
            }
            }

            Pattern mode = this.backgroundMode;
            Colour background = WHITE;

            JxlReportConfiguration configuration = getCurrentItemConfiguration();

            if (!configuration.isIgnoreCellBackground() && element.getBackcolor() != null) {
                mode = Pattern.SOLID;
                background = getWorkbookColour(element.getBackcolor(), true);
            }

            if (element.getModeValue() == ModeEnum.OPAQUE) {
                background = getWorkbookColour(element.getBackcolor(), true);
            }

            Colour forecolor = getWorkbookColour(element.getLineBox().getPen().getLineColor());

            WritableFont cellFont2 = this.getLoadedFont(getDefaultFont(), forecolor.getValue(), getLocale());

            WritableCellFormat cellStyle2 = getLoadedCellStyle(mode, background, cellFont2,
                    new BoxStyle(element), isCellLocked(element));

            addBlankElement(cellStyle2, repeatValue, currentColumnName);
            try {
                int colIndex = columnNamesMap.get(currentColumnName);
                WritableImage image = new WritableImage(colIndex, rowIndex, 1, 1, imageData);
                ImageAnchorTypeEnum imageAnchorType = ImageAnchorTypeEnum.getByName(JRPropertiesUtil
                        .getOwnProperty(element, XlsReportConfiguration.PROPERTY_IMAGE_ANCHOR_TYPE));
                if (imageAnchorType == null) {
                    imageAnchorType = configuration.getImageAnchorType();
                    if (imageAnchorType == null) {
                        imageAnchorType = ImageAnchorTypeEnum.MOVE_NO_SIZE;
                    }
                }
                setAnchorType(image, imageAnchorType);
                sheet.addImage(image);
            } catch (Exception ex) {
                throw new JRException("The cell cannot be added", ex);
            } catch (Error err) {
                throw new JRException("The cell cannot be added", err);
            }
        }
    }
}

From source file:net.sf.jasperreports.engine.export.JExcelApiExporter.java

public void exportImage(JRPrintImage element, JRExporterGridCell gridCell, int col, int row, int emptyCols,
        int yCutsRow, JRGridLayout layout) throws JRException {
    addMergeRegion(gridCell, col, row);/*from   www.  j a v  a 2s  .c  o m*/

    int topPadding = Math.max(element.getLineBox().getTopPadding().intValue(),
            getImageBorderCorrection(element.getLineBox().getTopPen()));
    int leftPadding = Math.max(element.getLineBox().getLeftPadding().intValue(),
            getImageBorderCorrection(element.getLineBox().getLeftPen()));
    int bottomPadding = Math.max(element.getLineBox().getBottomPadding().intValue(),
            getImageBorderCorrection(element.getLineBox().getBottomPen()));
    int rightPadding = Math.max(element.getLineBox().getRightPadding().intValue(),
            getImageBorderCorrection(element.getLineBox().getRightPen()));

    int availableImageWidth = element.getWidth() - leftPadding - rightPadding;
    availableImageWidth = availableImageWidth < 0 ? 0 : availableImageWidth;

    int availableImageHeight = element.getHeight() - topPadding - bottomPadding;
    availableImageHeight = availableImageHeight < 0 ? 0 : availableImageHeight;

    Renderable renderer = element.getRenderable();

    if (renderer != null && availableImageWidth > 0 && availableImageHeight > 0) {
        if (renderer.getTypeValue() == RenderableTypeEnum.IMAGE) {
            // Image renderers are all asked for their image data and dimension at some point. 
            // Better to test and replace the renderer now, in case of lazy load error.
            renderer = RenderableUtil.getInstance(jasperReportsContext).getOnErrorRendererForImageData(renderer,
                    element.getOnErrorTypeValue());
            if (renderer != null) {
                renderer = RenderableUtil.getInstance(jasperReportsContext)
                        .getOnErrorRendererForDimension(renderer, element.getOnErrorTypeValue());
            }
        } else {
            renderer = new JRWrappingSvgRenderer(renderer,
                    new Dimension(element.getWidth(), element.getHeight()),
                    ModeEnum.OPAQUE == element.getModeValue() ? element.getBackcolor() : null);
        }
    } else {
        renderer = null;
    }

    if (renderer != null) {
        int normalWidth = availableImageWidth;
        int normalHeight = availableImageHeight;

        Dimension2D dimension = renderer.getDimension(jasperReportsContext);
        if (dimension != null) {
            normalWidth = (int) dimension.getWidth();
            normalHeight = (int) dimension.getHeight();
        }

        float xalignFactor = 0f;
        switch (element.getHorizontalAlignmentValue()) {
        case RIGHT: {
            xalignFactor = 1f;
            break;
        }
        case CENTER: {
            xalignFactor = 0.5f;
            break;
        }
        case LEFT:
        default: {
            xalignFactor = 0f;
            break;
        }
        }

        float yalignFactor = 0f;
        switch (element.getVerticalAlignmentValue()) {
        case BOTTOM: {
            yalignFactor = 1f;
            break;
        }
        case MIDDLE: {
            yalignFactor = 0.5f;
            break;
        }
        case TOP:
        default: {
            yalignFactor = 0f;
            break;
        }
        }

        byte[] imageData = null;
        int topOffset = 0;
        int leftOffset = 0;
        int bottomOffset = 0;
        int rightOffset = 0;

        switch (element.getScaleImageValue()) {
        case CLIP: {
            int dpi = getPropertiesUtil().getIntegerProperty(Renderable.PROPERTY_IMAGE_DPI, 72);
            double scale = dpi / 72d;

            BufferedImage bi = new BufferedImage((int) (scale * availableImageWidth),
                    (int) (scale * availableImageHeight), BufferedImage.TYPE_INT_ARGB);

            Graphics2D grx = bi.createGraphics();
            grx.scale(scale, scale);
            grx.clip(new Rectangle(0, 0, availableImageWidth, availableImageHeight));

            renderer.render(jasperReportsContext, grx,
                    new Rectangle((int) (xalignFactor * (availableImageWidth - normalWidth)),
                            (int) (yalignFactor * (availableImageHeight - normalHeight)), normalWidth,
                            normalHeight));

            topOffset = topPadding;
            leftOffset = leftPadding;
            bottomOffset = bottomPadding;
            rightOffset = rightPadding;

            imageData = JRImageLoader.getInstance(jasperReportsContext).loadBytesFromAwtImage(bi,
                    ImageTypeEnum.PNG);

            break;
        }
        case FILL_FRAME: {
            topOffset = topPadding;
            leftOffset = leftPadding;
            bottomOffset = bottomPadding;
            rightOffset = rightPadding;

            imageData = renderer.getImageData(jasperReportsContext);

            break;
        }
        case RETAIN_SHAPE:
        default: {
            if (element.getHeight() > 0) {
                double ratio = (double) normalWidth / (double) normalHeight;

                if (ratio > (double) availableImageWidth / (double) availableImageHeight) {
                    normalWidth = availableImageWidth;
                    normalHeight = (int) (availableImageWidth / ratio);
                } else {
                    normalWidth = (int) (availableImageHeight * ratio);
                    normalHeight = availableImageHeight;
                }

                topOffset = topPadding + (int) (yalignFactor * (availableImageHeight - normalHeight));
                leftOffset = leftPadding + (int) (xalignFactor * (availableImageWidth - normalWidth));
                bottomOffset = bottomPadding
                        + (int) ((1f - yalignFactor) * (availableImageHeight - normalHeight));
                rightOffset = rightPadding + (int) ((1f - xalignFactor) * (availableImageWidth - normalWidth));

                imageData = renderer.getImageData(jasperReportsContext);
            }

            break;
        }
        }

        Pattern mode = this.backgroundMode;
        Colour background = WHITE;

        JxlReportConfiguration configuration = getCurrentItemConfiguration();

        if (!configuration.isIgnoreCellBackground() && gridCell.getCellBackcolor() != null) {
            mode = Pattern.SOLID;
            background = getWorkbookColour(gridCell.getCellBackcolor(), true);
        }

        if (element.getModeValue() == ModeEnum.OPAQUE) {
            background = getWorkbookColour(element.getBackcolor(), true);
        }

        Colour forecolor = getWorkbookColour(element.getLineBox().getPen().getLineColor());

        WritableFont cellFont2 = this.getLoadedFont(getDefaultFont(), forecolor.getValue(), getLocale());

        WritableCellFormat cellStyle2 = getLoadedCellStyle(mode, background, cellFont2, gridCell,
                isCellLocked(element));

        if (!configuration.isIgnoreAnchors() && element.getAnchorName() != null) {
            int lastCol = Math.max(0, col + gridCell.getColSpan() - 1);
            int lastRow = Math.max(0, row + gridCell.getRowSpan() - 1);
            workbook.addNameArea(element.getAnchorName(), sheet, col, row, lastCol, lastRow);
        }

        Boolean ignoreHyperlink = HyperlinkUtil
                .getIgnoreHyperlink(XlsReportConfiguration.PROPERTY_IGNORE_HYPERLINK, element);
        if (ignoreHyperlink == null) {
            ignoreHyperlink = configuration.isIgnoreHyperlink();
        }
        if (!ignoreHyperlink) {
            exportHyperlink(element, "", gridCell, col, row);
        }

        try {
            sheet.addCell(new Blank(col, row, cellStyle2));
            double leftPos = getColumnRelativePosition(layout, col, leftOffset);
            double topPos = getRowRelativePosition(layout, yCutsRow, topOffset);
            double rightPos = getColumnRelativePosition(layout, col, element.getWidth() - rightOffset);
            double bottomPos = getRowRelativePosition(layout, yCutsRow, element.getHeight() - bottomOffset);
            WritableImage image = new WritableImage(col + leftPos, row + topPos, rightPos - leftPos,
                    bottomPos - topPos, imageData);

            ImageAnchorTypeEnum imageAnchorType = ImageAnchorTypeEnum.getByName(JRPropertiesUtil
                    .getOwnProperty(element, XlsReportConfiguration.PROPERTY_IMAGE_ANCHOR_TYPE));
            if (imageAnchorType == null) {
                imageAnchorType = configuration.getImageAnchorType();
                if (imageAnchorType == null) {
                    imageAnchorType = ImageAnchorTypeEnum.MOVE_NO_SIZE;
                }
            }
            setAnchorType(image, imageAnchorType);
            sheet.addImage(image);
        } catch (Exception ex) {
            throw new JRException("The cell cannot be added", ex);
        } catch (Error err) {
            throw new JRException("The cell cannot be added", err);
        }
    }
}

From source file:forseti.JUtil.java

public static synchronized Image generarImagenMensaje(String mensaje, String nombreFuente, int tamanioFuente) {
    Frame f = new Frame();
    f.addNotify();//from   w  w  w  .  j  a v a2 s  .c o m
    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
    env.getAvailableFontFamilyNames();
    Font fuente = new Font(nombreFuente, Font.PLAIN, tamanioFuente);
    FontMetrics medidas = f.getFontMetrics(fuente);
    int anchoMensaje = medidas.stringWidth(mensaje);
    int lineaBaseX = anchoMensaje / 10;
    int ancho = anchoMensaje + 2 * (lineaBaseX + tamanioFuente);
    int alto = tamanioFuente * 7 / 2;
    int lineaBaseY = alto * 8 / 10;
    Image imagenMensaje = f.createImage(ancho, alto);
    Graphics2D g2d = (Graphics2D) imagenMensaje.getGraphics();
    g2d.setFont(fuente);
    g2d.translate(lineaBaseX, lineaBaseY);
    g2d.setPaint(Color.lightGray);
    AffineTransform origTransform = g2d.getTransform();
    g2d.shear(-0.95, 0);
    g2d.scale(1, 3);
    g2d.drawString(mensaje, 0, 0);
    g2d.setTransform(origTransform);
    g2d.setPaint(Color.black);
    g2d.drawString(mensaje, 0, 0);

    return (imagenMensaje);
}

From source file:me.solhub.simple.engine.DebugLocationsStructure.java

@Override
protected void draw() {
    Graphics2D g = (Graphics2D) getGraphics();
    Graphics2D bbg = (Graphics2D) _backBuffer.getGraphics();

    //anti-aliasing code
    //        bbg.setRenderingHint(
    //                RenderingHints.KEY_TEXT_ANTIALIASING,
    //                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    //        bbg.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );

    bbg.setColor(Color.WHITE);//from  w  ww.ja  va2  s.  c  om
    bbg.fillRect(0, 0, _windowWidth, _windowHeight);

    bbg.translate(_xOffset, _yOffset);

    // draw destinations
    bbg.setColor(_simState.startingDestination.getColor());
    bbg.drawOval(-(int) _simState.startingDestination.getRadius(),
            -(int) _simState.startingDestination.getRadius(),
            (int) _simState.startingDestination.getRadius() * 2,
            (int) _simState.startingDestination.getRadius() * 2);
    Iterator<Entry<Vector2D, Color>> blah = _destinationColors.entrySet().iterator();
    double destinationRadius = _simState.getDestinationRadius();
    while (blah.hasNext()) {
        Entry<Vector2D, Color> temp = blah.next();
        bbg.setColor(temp.getValue());
        //calculate center coordinate
        int x = (int) (temp.getKey().getX() - (destinationRadius));
        int y = (int) (temp.getKey().getY() - (destinationRadius));
        //drawOval draws a circle inside a rectangle
        bbg.drawOval(x, y, _simState.getDestinationRadius() * 2, _simState.getDestinationRadius() * 2);
    }

    // draw each of the agents
    Iterator<Agent> agentIter = _simState.getAgentIterator();
    while (agentIter.hasNext()) {
        Agent temp = agentIter.next();
        if (temp.isAlive()) {
            // decide whether to color for destination or group
            //                if( isDestinationColors )
            //                {
            //                    // if stopped then blink white and destination color
            //                    if( temp.hasReachedDestination() )
            //                    {
            //                        if( pulseWhite % 20 == 0 )
            //                        {
            //                            bbg.setColor( Color.WHITE );
            //                        }
            //                        else
            //                        {
            //                            bbg.setColor( temp.getDestinationColor() );
            //                        }
            //                    }
            //                    else
            //                    {
            //                        bbg.setColor( temp.getDestinationColor() );
            //                    }
            //                }
            //                else
            //                {
            //                    // if stopped then blink black and white
            //                    if( temp.hasReachedDestination() )
            //                    {
            //                        if( pulseWhite % 20 == 0 )
            //                        {
            //                            bbg.setColor( Color.WHITE );
            //                        }
            //                        else
            //                        {
            //                            bbg.setColor( temp.getGroup().getGroupColor() );
            //                        }
            //                    }
            //                    //set color to red if cancelled and global and not multiple initiators
            //                    else if(temp.getCurrentDecision().getDecision().getDecisionType().equals(
            //                            DecisionType.CANCELLATION ) 
            //                            && _simState.getCommunicationType().equals( "global" )
            //                            && !Agent.canMultipleInitiate()
            //                            )
            //                    {
            //                        bbg.setColor( Color.RED );
            //                    }
            //                    else
            //                    {
            //                        bbg.setColor( temp.getGroup().getGroupColor() );
            //                    }
            //                }

            double dx = temp.getCurrentDestination().getX() - temp.getCurrentLocation().getX();
            double dy = temp.getCurrentDestination().getY() - temp.getCurrentLocation().getY();
            double heading = Math.atan2(dy, dx);
            Utils.drawDirectionalTriangle(bbg, heading - Math.PI / 2, temp.getCurrentLocation().getX(),
                    temp.getCurrentLocation().getY(), 7, temp.getPreferredDestination().getColor(),
                    temp.getGroup().getGroupColor());

            //                bbg.fillOval( (int) temp.getCurrentLocation().getX() - _agentSize,
            //                        (int) temp.getCurrentLocation().getY() - _agentSize , _agentSize * 2, _agentSize * 2 );
        }
    }
    pulseWhite++;
    bbg.setColor(Color.BLACK);
    // the total number of groups
    bbg.setFont(_infoFont);

    bbg.drawString("Run: " + (_simState.getCurrentSimulationRun() + 1), _fontXOffset, _fontYOffset);
    bbg.drawString("Time: " + _simState.getSimulationTime(), _fontXOffset, _fontYOffset + _fontSize);
    bbg.drawString("Delay: " + LIVE_DELAY, _fontXOffset, _fontYOffset + _fontSize * 2);

    if (_simState.getCommunicationType().equals("global") && !Agent.canMultipleInitiate()) {
        String initiatorName = "None";
        if (_initiatingAgent != null) {
            initiatorName = _initiatingAgent.getId().toString();
        }
        bbg.drawString("Init: " + initiatorName, _fontXOffset, _fontYOffset + _fontSize * 3);
        bbg.drawString("Followers: " + _numberFollowing, _fontXOffset, _fontYOffset + _fontSize * 4);
    } else {
        bbg.drawString("Groups: " + _simState.getNumberGroups(), _fontXOffset, _fontYOffset + _fontSize * 3);
        bbg.drawString("Reached: " + _simState.numReachedDestination, _fontXOffset,
                _fontYOffset + _fontSize * 4);
        bbg.drawString("Inits: " + _simState.numInitiating, _fontXOffset, _fontYOffset + _fontSize * 5);
        bbg.drawString("Eaten: " + _simState.getPredator().getTotalAgentsEaten(), _fontXOffset,
                _fontYOffset + _fontSize * 6);
    }

    g.scale(_zoom, _zoom);
    g.drawImage(_backBuffer, 0, 0, this);
    if (SHOULD_VIDEO) {

        // setup to save to a png
        BufferedImage buff = new BufferedImage(_windowWidth, _windowHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D temp = (Graphics2D) buff.getGraphics();
        temp.scale(8, 4);
        temp.drawImage(_backBuffer, 0, 0, this);
        // sub-directory
        File dir = new File("video");
        dir.mkdir();
        // format string for filename
        String filename = String.format("video/run-%03d-time-%05d.png", _simState.getCurrentSimulationRun(),
                _simState.getSimulationTime());
        File outputfile = new File(filename);
        // save it
        try {
            ImageIO.write(buff, "png", outputfile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:lu.fisch.unimozer.Diagram.java

@Override
public int print(Graphics g, PageFormat pageFormat, int page) throws PrinterException {
    /*//from  ww  w. j  a v  a  2 s  . c  o  m
        // clone paper
        Paper originalPaper = pageFormat.getPaper();
        Paper paper = new Paper();
        // resize it
        paper.setSize(originalPaper.getWidth(), originalPaper.getHeight());
        paper.setImageableArea(
                originalPaper.getImageableX(),
                originalPaper.getImageableY()+30,
                originalPaper.getImageableWidth(),
                originalPaper.getImageableHeight()-60);
        // apply it
        pageFormat.setPaper(paper);
    */
    /*                Paper paper = new Paper();
        paper.setSize(pageFormat.getWidth(),pageFormat.getHeight());
                
        double paddingLeftRight = pageFormat.getImageableX();
        double paddingTopBottom = pageFormat.getImageableY()+30;
        if (pageFormat.getOrientation()==PageFormat.LANDSCAPE)
        {
            paddingLeftRight = 60;
            paddingTopBottom = 60;
        }
        paper.setImageableArea(paddingLeftRight,
                               paddingTopBottom,
                               pageFormat.getWidth()-2*paddingLeftRight,
                               pageFormat.getHeight()-2*paddingTopBottom);
        pageFormat.setPaper(paper);*/

    if (page == 0) {
        pageList.clear();
        if (printOptions.printCode() == true) {
            /*Set<String> set = classes.keySet();
            Iterator<String> itr = set.iterator();
            while (itr.hasNext())
            {
              String str = itr.next();*/

            /* let's try this one ... */
            for (Entry<String, MyClass> entry : classes.entrySet()) {
                // get the actual class ...
                String str = entry.getKey();

                MyClass thisClass = classes.get(str);
                CodeEditor edit = new CodeEditor();
                edit.setFont(new Font(edit.getFont().getName(), Font.PLAIN, printOptions.getFontSize()));

                String code = "";
                // get code, depending on JavaDoc filter
                if (printOptions.printJavaDoc())
                    code = thisClass.getContent().getText();
                else
                    code = thisClass.getJavaCodeCommentless();

                // filter double lines
                if (printOptions.filterDoubleLines()) {
                    StringList sl = StringList.explode(code, "\n");
                    sl.removeDoubleEmptyLines();
                    code = sl.getText();
                }

                //edit.setDiagram(diagram);
                edit.setCode(code);

                // resize the picture
                PageFormat pf = (PageFormat) pageFormat.clone();
                Paper pa = pf.getPaper();
                pa.setImageableArea(pa.getImageableX(), pa.getImageableY() + 20, pa.getImageableWidth(),
                        pa.getImageableHeight() - 40);
                pf.setPaper(pa);

                //sheets = new Vector<BufferedImage>();
                int p = 0;
                int result = 0;
                do {
                    /*BufferedImage img = new BufferedImage((int) pageFormat.getImageableWidth(),(int) pageFormat.getImageableHeight(),BufferedImage.TYPE_INT_RGB );
                    img.getGraphics().setColor(Color.WHITE);
                    img.getGraphics().fillRect(0,0,(int) pageFormat.getImageableWidth(),(int) pageFormat.getImageableHeight());*/

                    BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
                    result = edit.print(img.createGraphics(), pf, p);
                    if (result == PAGE_EXISTS) {
                        //sheets.add(img);
                        pageList.add(str);
                        p++;
                    }
                } while (result == PAGE_EXISTS);

                //edit.print(g, pf, p);
                edit = null;
                System.gc();
            }
        }
    }

    if (page == 0 && printOptions.printDiagram() == true) {
        Graphics2D g2d = (Graphics2D) g;

        int yOffset = (int) pageFormat.getImageableY();

        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

        double sX = (pageFormat.getImageableWidth() - 1) / getDiagramWidth();
        double sY = (pageFormat.getImageableHeight() - 1 - 40) / getDiagramHeight();
        double sca = Math.min(sX, sY);
        if (sca > 1) {
            sca = 1;
        }
        g2d.translate(0, 20);
        g2d.scale(sca, sca);

        paint(g2d);

        g2d.scale(1 / sca, 1 / sca);
        g2d.translate(0, -(20));
        g2d.translate(-pageFormat.getImageableX(), -pageFormat.getImageableY());

        printHeaderFooter(g2d, pageFormat, page, new String());

        PageFormat pf = (PageFormat) pageFormat.clone();
        Paper pa = pf.getPaper();
        pa.setImageableArea(pa.getImageableX(), pa.getImageableY() + 20, pa.getImageableWidth(),
                pa.getImageableHeight() - 40);
        pf.setPaper(pa);

        // reset the paper
        //pageFormat.setPaper(originalPaper);
        return (PAGE_EXISTS);
    } else {
        int origPage = page;

        if (printOptions.printDiagram() == true)
            page--;

        if (page >= pageList.size() || printOptions.printCode() == false)
            return (NO_SUCH_PAGE);
        else {
            String mc = pageList.get(page);
            page--;
            int p = 0;
            while (page >= 0) {
                if (pageList.get(page).equals(mc))
                    p++;
                page--;
            }
            MyClass thisClass = classes.get(mc);

            CodeEditor edit = new CodeEditor();
            edit.setFont(new Font(edit.getFont().getName(), Font.PLAIN, printOptions.getFontSize()));

            String code = "";
            // get code, depending on JavaDoc filter
            if (printOptions.printJavaDoc())
                code = thisClass.getContent().getText();
            else
                code = thisClass.getJavaCodeCommentless();

            // filter double lines
            if (printOptions.filterDoubleLines()) {
                StringList sl = StringList.explode(code, "\n");
                sl.removeDoubleEmptyLines();
                code = sl.getText();
            }

            edit.setCode(code);

            printHeaderFooter(g, pageFormat, origPage, thisClass.getShortName());

            PageFormat pf = (PageFormat) pageFormat.clone();
            Paper pa = pf.getPaper();
            pa.setImageableArea(pa.getImageableX(), pa.getImageableY() + 20, pa.getImageableWidth(),
                    pa.getImageableHeight() - 40);
            pf.setPaper(pa);

            edit.print(g, pf, p);
            edit = null;
            System.gc();

            // reset the paper
            //pageFormat.setPaper(originalPaper);
            return (PAGE_EXISTS);
        }
    }
}

From source file:org.forester.archaeopteryx.TreePanel.java

final void paintPhylogeny(final Graphics2D g, final boolean to_pdf, final boolean to_graphics_file,
        final int graphics_file_width, final int graphics_file_height, final int graphics_file_x,
        final int graphics_file_y) {
    /* GUILHEM_BEG */
    _query_sequence = _control_panel.getSelectedQuerySequence();
    /* GUILHEM_END */
    // Color the background
    if (!to_pdf) {
        final Rectangle r = getVisibleRect();
        if (!getOptions().isBackgroundColorGradient() || getOptions().isPrintBlackAndWhite()) {
            g.setColor(getTreeColorSet().getBackgroundColor());
            if (!to_graphics_file) {
                g.fill(r);/* w w  w.  jav a  2 s  .c om*/
            } else {
                if (getOptions().isPrintBlackAndWhite()) {
                    g.setColor(Color.WHITE);
                }
                g.fillRect(graphics_file_x, graphics_file_y, graphics_file_width, graphics_file_height);
            }
        } else {
            if (!to_graphics_file) {
                g.setPaint(new GradientPaint(r.x, r.y, getTreeColorSet().getBackgroundColor(), r.x,
                        r.y + r.height, getTreeColorSet().getBackgroundColorGradientBottom()));
                g.fill(r);
            } else {
                g.setPaint(new GradientPaint(graphics_file_x, graphics_file_y,
                        getTreeColorSet().getBackgroundColor(), graphics_file_x,
                        graphics_file_y + graphics_file_height,
                        getTreeColorSet().getBackgroundColorGradientBottom()));
                g.fillRect(graphics_file_x, graphics_file_y, graphics_file_width, graphics_file_height);
            }
        }
        g.setStroke(new BasicStroke(1));
    } else {
        g.setStroke(new BasicStroke(getOptions().getPrintLineWidth()));
    }
    if ((getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.UNROOTED)
            && (getPhylogenyGraphicsType() != PHYLOGENY_GRAPHICS_TYPE.CIRCULAR)) {
        _external_node_index = 0;
        // Position starting X of tree
        if (!_phylogeny.isRooted()) {
            _phylogeny.getRoot().setXcoord(TreePanel.MOVE);
        } else if ((_phylogeny.getRoot().getDistanceToParent() > 0.0) && getControlPanel().isDrawPhylogram()) {
            _phylogeny.getRoot().setXcoord((float) (TreePanel.MOVE
                    + (_phylogeny.getRoot().getDistanceToParent() * getXcorrectionFactor())));
        } else {
            _phylogeny.getRoot().setXcoord(TreePanel.MOVE + getXdistance());
        }
        // Position starting Y of tree
        _phylogeny.getRoot().setYcoord(
                (getYdistance() * _phylogeny.getRoot().getNumberOfExternalNodes()) + (TreePanel.MOVE / 2.0f));
        final int dynamic_hiding_factor = (int) (getTreeFontSet()._fm_large.getHeight()
                / (1.5 * getYdistance()));
        if (getControlPanel().isDynamicallyHideData()) {
            if (dynamic_hiding_factor > 1) {
                getControlPanel().setDynamicHidingIsOn(true);
            } else {
                getControlPanel().setDynamicHidingIsOn(false);
            }
        }
        final PhylogenyNodeIterator it;
        for (it = _phylogeny.iteratorPreorder(); it.hasNext();) {
            paintNodeRectangular(g, it.next(), to_pdf,
                    getControlPanel().isDynamicallyHideData() && (dynamic_hiding_factor > 1),
                    dynamic_hiding_factor, to_graphics_file);
        }
        if (getOptions().isShowScale()) {
            if (!(to_graphics_file || to_pdf)) {
                paintScale(g, getVisibleRect().x, getVisibleRect().y + getVisibleRect().height, to_pdf,
                        to_graphics_file);
            } else {
                paintScale(g, graphics_file_x, graphics_file_y + graphics_file_height, to_pdf,
                        to_graphics_file);
            }
        }
        if (getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf) {
            paintPhylogenyLite(g);
        }
    } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.UNROOTED) {
        if (getControlPanel().getDynamicallyHideData() != null) {
            getControlPanel().setDynamicHidingIsOn(false);
        }
        final double angle = getStartingAngle();
        final boolean radial_labels = getOptions().getNodeLabelDirection() == NODE_LABEL_DIRECTION.RADIAL;
        _dynamic_hiding_factor = 0;
        if (getControlPanel().isDynamicallyHideData()) {
            _dynamic_hiding_factor = (int) ((getTreeFontSet()._fm_large.getHeight() * 1.5
                    * getPhylogeny().getNumberOfExternalNodes()) / (TWO_PI * 10));
        }
        if (getControlPanel().getDynamicallyHideData() != null) {
            if (_dynamic_hiding_factor > 1) {
                getControlPanel().setDynamicHidingIsOn(true);
            } else {
                getControlPanel().setDynamicHidingIsOn(false);
            }
        }
        paintUnrooted(_phylogeny.getRoot(), angle, (float) (angle + 2 * Math.PI), radial_labels, g, to_pdf,
                to_graphics_file);
        if (getOptions().isShowScale()) {
            if (!(to_graphics_file || to_pdf)) {
                paintScale(g, getVisibleRect().x, getVisibleRect().y + getVisibleRect().height, to_pdf,
                        to_graphics_file);
            } else {
                paintScale(g, graphics_file_x, graphics_file_y + graphics_file_height, to_pdf,
                        to_graphics_file);
            }
        }
        if (getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf) {
            g.setColor(getTreeColorSet().getOvColor());
            paintUnrootedLite(_phylogeny.getRoot(), angle, angle + 2 * Math.PI, g,
                    (getUrtFactorOv() / (getVisibleRect().width / getOvMaxWidth())));
            paintOvRectangle(g);
        }
    } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.CIRCULAR) {
        final int radius = (int) ((Math.min(getPreferredSize().getWidth(), getPreferredSize().getHeight()) / 2)
                - (MOVE + getLongestExtNodeInfo()));
        final int d = radius + MOVE + getLongestExtNodeInfo();
        _dynamic_hiding_factor = 0;
        if (getControlPanel().isDynamicallyHideData() && (radius > 0)) {
            _dynamic_hiding_factor = (int) ((getTreeFontSet()._fm_large.getHeight() * 1.5
                    * getPhylogeny().getNumberOfExternalNodes()) / (TWO_PI * radius));
        }
        if (getControlPanel().getDynamicallyHideData() != null) {
            if (_dynamic_hiding_factor > 1) {
                getControlPanel().setDynamicHidingIsOn(true);
            } else {
                getControlPanel().setDynamicHidingIsOn(false);
            }
        }
        paintCircular(_phylogeny, getStartingAngle(), d, d, radius > 0 ? radius : 0, g, to_pdf,
                to_graphics_file);
        if (getOptions().isShowOverview() && isOvOn() && !to_graphics_file && !to_pdf) {
            final int radius_ov = (int) (getOvMaxHeight() < getOvMaxWidth() ? getOvMaxHeight() / 2
                    : getOvMaxWidth() / 2);
            double x_scale = 1.0;
            double y_scale = 1.0;
            int x_pos = getVisibleRect().x + getOvXPosition();
            int y_pos = getVisibleRect().y + getOvYPosition();
            if (getWidth() > getHeight()) {
                x_scale = (double) getHeight() / getWidth();
                x_pos = ForesterUtil.roundToInt(x_pos / x_scale);
            } else {
                y_scale = (double) getWidth() / getHeight();
                y_pos = ForesterUtil.roundToInt(y_pos / y_scale);
            }
            _at = g.getTransform();
            g.scale(x_scale, y_scale);
            paintCircularLite(_phylogeny, getStartingAngle(), x_pos + radius_ov, y_pos + radius_ov,
                    (int) (radius_ov - (getLongestExtNodeInfo()
                            / (getVisibleRect().width / getOvRectangle().getWidth()))),
                    g);
            g.setTransform(_at);
            paintOvRectangle(g);
        }
    }
}

From source file:org.apache.fop.render.bitmap.AbstractBitmapDocumentHandler.java

/** {@inheritDoc} */
public IFPainter startPageContent() throws IFException {
    int bitmapWidth;
    int bitmapHeight;
    double scale;
    Point2D offset = null;//from w ww. jav  a2 s. c  o  m
    if (targetBitmapSize != null) {
        //Fit the generated page proportionally into the given rectangle (in pixels)
        double scale2w = 1000 * targetBitmapSize.width / this.currentPageDimensions.getWidth();
        double scale2h = 1000 * targetBitmapSize.height / this.currentPageDimensions.getHeight();
        bitmapWidth = targetBitmapSize.width;
        bitmapHeight = targetBitmapSize.height;

        //Centering the page in the given bitmap
        offset = new Point2D.Double();
        if (scale2w < scale2h) {
            scale = scale2w;
            double h = this.currentPageDimensions.height * scale / 1000;
            offset.setLocation(0, (bitmapHeight - h) / 2.0);
        } else {
            scale = scale2h;
            double w = this.currentPageDimensions.width * scale / 1000;
            offset.setLocation((bitmapWidth - w) / 2.0, 0);
        }
    } else {
        //Normal case: just scale according to the target resolution
        scale = scaleFactor * getUserAgent().getTargetResolution()
                / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION;
        bitmapWidth = (int) ((this.currentPageDimensions.width * scale / 1000f) + 0.5f);
        bitmapHeight = (int) ((this.currentPageDimensions.height * scale / 1000f) + 0.5f);
    }

    //Set up bitmap to paint on
    this.currentImage = createBufferedImage(bitmapWidth, bitmapHeight);
    Graphics2D graphics2D = this.currentImage.createGraphics();

    // draw page background
    if (!getSettings().hasTransparentPageBackground()) {
        graphics2D.setBackground(getSettings().getPageBackgroundColor());
        graphics2D.setPaint(getSettings().getPageBackgroundColor());
        graphics2D.fillRect(0, 0, bitmapWidth, bitmapHeight);
    }

    //Set rendering hints
    graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
            RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    if (getSettings().isAntiAliasingEnabled() && this.currentImage.getColorModel().getPixelSize() > 1) {
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    } else {
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
        graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
    }
    if (getSettings().isQualityRenderingEnabled()) {
        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    } else {
        graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
    }
    graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

    //Set up initial coordinate system for the page
    if (offset != null) {
        graphics2D.translate(offset.getX(), offset.getY());
    }
    graphics2D.scale(scale / 1000f, scale / 1000f);

    return new Java2DPainter(graphics2D, getContext(), getFontInfo());
}