Example usage for java.awt Rectangle getWidth

List of usage examples for java.awt Rectangle getWidth

Introduction

In this page you can find the example usage for java.awt Rectangle getWidth.

Prototype

public double getWidth() 

Source Link

Document

Returns the width of the bounding Rectangle in double precision.

Usage

From source file:CopyAreaPerformance.java

protected void paintComponent(Graphics g) {
    long startTime = System.nanoTime();
    // prevVX is set to -10000 when first enabled
    if (useCopyArea && prevVX > -9999) {
        // Most of this code determines the proper areas to copy and clip
        int scrollX = viewX - prevVX;
        int scrollY = viewY - prevVY;
        int copyFromY, copyFromX;
        int clipFromY, clipFromX;
        if (scrollX == 0) {
            // vertical scroll
            if (scrollY < 0) {
                copyFromY = 0;//w ww .  j ava2s.  co  m
                clipFromY = 0;
            } else {
                copyFromY = scrollY;
                clipFromY = getHeight() - scrollY;
            }
            // copy the old content, set the clip to the new area
            g.copyArea(0, copyFromY, getWidth(), getHeight() - Math.abs(scrollY), 0, -scrollY);
            g.setClip(0, clipFromY, getWidth(), Math.abs(scrollY));
        } else {
            // horizontal scroll
            if (scrollX < 0) {
                copyFromX = 0;
                clipFromX = 0;
            } else {
                copyFromX = scrollX;
                clipFromX = getWidth() - scrollX;
            }
            // copy the old content, set the clip to the new area
            g.copyArea(copyFromX, 0, getWidth() - Math.abs(scrollX), getHeight(), -scrollX, 0);
            g.setClip(clipFromX, 0, Math.abs(scrollX), getHeight());
        }
    }
    // Track previous view position for next scrolling operation
    prevVX = viewX;
    prevVY = viewY;
    // Get the clip in case we need it later
    Rectangle clipRect = g.getClip().getBounds();
    int clipL = (int) (clipRect.getX());
    int clipT = (int) (clipRect.getY());
    int clipR = (int) (clipRect.getMaxX());
    int clipB = (int) (clipRect.getMaxY());
    g.setColor(Color.WHITE);
    g.fillRect(clipL, clipT, (int) clipRect.getWidth(), (int) clipRect.getHeight());
    for (int column = 0; column < 256; ++column) {
        int x = column * (SMILEY_SIZE + PADDING) - viewX;
        if (useClip) {
            if (x > clipR || (x + (SMILEY_SIZE + PADDING)) < clipL) {
                // trivial reject; outside to the left or right
                continue;
            }
        }
        for (int row = 0; row < 256; ++row) {
            int y = row * (SMILEY_SIZE + PADDING) - viewY;
            if (useClip) {
                if (y > clipB || (y + (SMILEY_SIZE + PADDING)) < clipT) {
                    // trivial reject; outside to the top or bottom
                    continue;
                }
            }
            Color faceColor = new Color(column, row, 0);
            drawSmiley(g, faceColor, x, y);
        }
    }
    long stopTime = System.nanoTime();
    System.out.println("Painted in " + ((stopTime - startTime) / 1000000) + " ms");
}

From source file:lu.lippmann.cdb.graph.GenericGraphViewImpl.java

@Override
public void autoFit() {
    final Rectangle visible = vv.getVisibleRect();
    //Add margin/*  www .jav  a2s.  c om*/
    int panelWidth = (int) visible.getWidth() - 10;
    int panelHeight = (int) visible.getHeight() - 10;
    fitGraphToSubPanel(panelWidth, panelHeight, 100.0d);
}

From source file:com.tulskiy.musique.system.configuration.Configuration.java

public void setRectangle(String key, Rectangle value) {
    if (value == null)
        remove(key);//from   w ww  .j  ava2s  .c  om
    else {
        String s = new Formatter().format("%d %d %d %d", (int) value.getX(), (int) value.getY(),
                (int) value.getWidth(), (int) value.getHeight()).toString();
        put(key, s);
    }
}

From source file:ch5ImageWriter.java

/**
 * write out the output image specified by index imageIndex using the
 * parameters specified by the ImageWriteParam object param
 *//*  w  ww .j  av  a2s .  c o m*/
public void write(IIOMetadata metadata, IIOImage iioimage, ImageWriteParam param) {
    Node root = null;
    Node dimensionsElementNode = null;

    if (iioimage.getRenderedImage() != null)
        raster = iioimage.getRenderedImage().getData();
    else
        raster = iioimage.getRaster();

    /*
     * since this format allows you to write multiple images, the
     * streamMetadataWritten variable makes sure the stream metadata is
     * written only once
     */
    if (streamMetadataWritten == false) {
        if (metadata == null)
            metadata = getDefaultStreamMetadata(param);
        root = metadata.getAsTree("ch5.imageio.ch5stream_1.00");
        dimensionsElementNode = root.getFirstChild();
        Node numberImagesAttributeNode = dimensionsElementNode.getAttributes().getNamedItem("numberImages");
        String numberImages = numberImagesAttributeNode.getNodeValue();
        try {
            ios.writeBytes("5\n");
            ios.writeBytes(numberImages);
            ios.flush();
        } catch (IOException ioe) {
            System.err.println("IOException " + ioe.getMessage());
        }
        streamMetadataWritten = true;
    }

    String widthString;
    String heightString;
    IIOMetadata imageMetadata = (ch5ImageMetadata) iioimage.getMetadata();
    /*
     * don't really need image metadata object here since raster knows
     * necessary information
     */
    if (imageMetadata == null)
        imageMetadata = getDefaultImageMetadata(null, param);

    root = imageMetadata.getAsTree("ch5.imageio.ch5image_1.00");
    dimensionsElementNode = root.getFirstChild();

    Node widthAttributeNode = dimensionsElementNode.getAttributes().getNamedItem("imageWidth");
    widthString = widthAttributeNode.getNodeValue();

    Node heightAttributeNode = dimensionsElementNode.getAttributes().getNamedItem("imageHeight");
    heightString = heightAttributeNode.getNodeValue();

    int sourceWidth = Integer.parseInt(widthString);
    int sourceHeight = Integer.parseInt(heightString);
    int destinationWidth = -1;
    int destinationHeight = -1;
    int sourceRegionWidth = -1;
    int sourceRegionHeight = -1;
    int sourceRegionXOffset = -1;
    int sourceRegionYOffset = -1;
    int xSubsamplingFactor = -1;
    int ySubsamplingFactor = -1;

    if (param == null)
        param = getDefaultWriteParam();

    /*
     * get Rectangle object which will be used to clip the source image's
     * dimensions.
     */
    Rectangle sourceRegion = param.getSourceRegion();
    if (sourceRegion != null) {
        sourceRegionWidth = (int) sourceRegion.getWidth();
        sourceRegionHeight = (int) sourceRegion.getHeight();
        sourceRegionXOffset = (int) sourceRegion.getX();
        sourceRegionYOffset = (int) sourceRegion.getY();

        /*
         * correct for overextended source regions
         */
        if (sourceRegionXOffset + sourceRegionWidth > sourceWidth)
            destinationWidth = sourceWidth - sourceRegionXOffset;
        else
            destinationWidth = sourceRegionWidth;

        if (sourceRegionYOffset + sourceRegionHeight > sourceHeight)
            destinationHeight = sourceHeight - sourceRegionYOffset;
        else
            destinationHeight = sourceRegionHeight;
    } else {
        destinationWidth = sourceWidth;
        destinationHeight = sourceHeight;
        sourceRegionXOffset = sourceRegionYOffset = 0;
    }
    /*
     * get subsampling factors
     */
    xSubsamplingFactor = param.getSourceXSubsampling();
    ySubsamplingFactor = param.getSourceYSubsampling();

    destinationWidth = (destinationWidth - 1) / xSubsamplingFactor + 1;
    destinationHeight = (destinationHeight - 1) / ySubsamplingFactor + 1;

    byte[] sourceBuffer;
    byte[] destinationBuffer = new byte[destinationWidth];

    try {
        ios.writeBytes(new String("\n"));
        ios.writeBytes(new String(destinationWidth + "\n"));
        ios.writeBytes(new String(destinationHeight + "\n"));

        int jj;
        int index;
        for (int j = 0; j < sourceWidth; j++) {
            sourceBuffer = (byte[]) raster.getDataElements(0, j, sourceWidth, 1, null);
            jj = j - sourceRegionYOffset;
            if (jj % ySubsamplingFactor == 0) {
                jj /= ySubsamplingFactor;
                if ((jj >= 0) && (jj < destinationHeight)) {
                    for (int i = 0; i < destinationWidth; i++) {
                        index = sourceRegionXOffset + i * xSubsamplingFactor;
                        destinationBuffer[i] = sourceBuffer[index];
                    }
                    ios.write(destinationBuffer, 0, destinationWidth);
                    ios.flush();
                }
            }
        }
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
    }
}

From source file:org.geomajas.plugin.rasterizing.layer.RasterDirectLayer.java

protected void addImage(Graphics2D graphics, ImageResult imageResult, MapViewport viewport) throws IOException {
    Rectangle screenArea = viewport.getScreenArea();
    ReferencedEnvelope worldBounds = viewport.getBounds();
    // convert map bounds to application bounds
    double printScale = screenArea.getWidth() / worldBounds.getWidth();
    if (tileScale < 0) {
        tileScale = printScale;//from www .j  a v a  2 s .  co m
    }
    Envelope applicationBounds = new Envelope((worldBounds.getMinX()) * printScale,
            (worldBounds.getMaxX()) * printScale, -(worldBounds.getMinY()) * printScale,
            -(worldBounds.getMaxY()) * printScale);
    Bbox imageBounds = imageResult.getRasterImage().getBounds();
    // find transform between image bounds and application bounds
    double tx = (imageBounds.getX() * printScale / tileScale - applicationBounds.getMinX());
    double ty = (imageBounds.getY() * printScale / tileScale - applicationBounds.getMinY());
    BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageResult.getImage()));
    double scaleX = imageBounds.getWidth() / image.getWidth() * printScale / tileScale;
    double scaleY = imageBounds.getHeight() / image.getHeight() * printScale / tileScale;
    AffineTransform transform = new AffineTransform();
    transform.translate(tx, ty);
    transform.scale(scaleX, scaleY);
    if (log.isDebugEnabled()) {
        log.debug("adding image, width=" + image.getWidth() + ",height=" + image.getHeight() + ",x=" + tx
                + ",y=" + ty);
    }
    // opacity
    log.debug("before drawImage");
    // create a copy to apply transform
    Graphics2D g = (Graphics2D) graphics.create();
    // apply opacity to image off-graphics to avoid interference with whatever opacity model is used by graphics
    BufferedImage opaqueCopy = makeOpaque(image);
    g.drawImage(opaqueCopy, transform, null);
    log.debug("after drawImage");
}

From source file:ch5ImageReader.java

/**
 * read in the input image specified by index imageIndex using the
 * parameters specified by the ImageReadParam object param
 *//*  ww  w  .  j a  va2 s . c o m*/
public BufferedImage read(int imageIndex, ImageReadParam param) {

    checkIndex(imageIndex);

    if (isSeekForwardOnly())
        minIndex = imageIndex;
    else
        minIndex = 0;

    BufferedImage bimage = null;
    WritableRaster raster = null;

    /*
     * this method sets the image metadata so that we can use the getWidth
     * and getHeight methods
     */
    setImageMetadata(iis, imageIndex);

    int srcWidth = getWidth(imageIndex);
    int srcHeight = getHeight(imageIndex);

    // initialize values to -1
    int dstWidth = -1;
    int dstHeight = -1;
    int srcRegionWidth = -1;
    int srcRegionHeight = -1;
    int srcRegionXOffset = -1;
    int srcRegionYOffset = -1;
    int xSubsamplingFactor = -1;
    int ySubsamplingFactor = -1;
    if (param == null)
        param = getDefaultReadParam();

    Iterator imageTypes = getImageTypes(imageIndex);
    try {
        /*
         * get the destination BufferedImage which will be filled using the
         * input image's pixel data
         */
        bimage = getDestination(param, imageTypes, srcWidth, srcHeight);

        /*
         * get Rectangle object which will be used to clip the source
         * image's dimensions.
         */
        Rectangle srcRegion = param.getSourceRegion();
        if (srcRegion != null) {
            srcRegionWidth = (int) srcRegion.getWidth();
            srcRegionHeight = (int) srcRegion.getHeight();
            srcRegionXOffset = (int) srcRegion.getX();
            srcRegionYOffset = (int) srcRegion.getY();

            /*
             * correct for overextended source regions
             */
            if (srcRegionXOffset + srcRegionWidth > srcWidth)
                dstWidth = srcWidth - srcRegionXOffset;
            else
                dstWidth = srcRegionWidth;

            if (srcRegionYOffset + srcRegionHeight > srcHeight)
                dstHeight = srcHeight - srcRegionYOffset;
            else
                dstHeight = srcRegionHeight;
        } else {
            dstWidth = srcWidth;
            dstHeight = srcHeight;
            srcRegionXOffset = srcRegionYOffset = 0;
        }
        /*
         * get subsampling factors
         */
        xSubsamplingFactor = param.getSourceXSubsampling();
        ySubsamplingFactor = param.getSourceYSubsampling();

        /**
         * dstWidth and dstHeight should be equal to bimage.getWidth() and
         * bimage.getHeight() after these next two instructions
         */
        dstWidth = (dstWidth - 1) / xSubsamplingFactor + 1;
        dstHeight = (dstHeight - 1) / ySubsamplingFactor + 1;
    } catch (IIOException e) {
        System.err.println("Can't create destination BufferedImage");
    }
    raster = bimage.getWritableTile(0, 0);

    /*
     * using the parameters specified by the ImageReadParam object, read the
     * image image data into the destination BufferedImage
     */
    byte[] srcBuffer = new byte[srcWidth];
    byte[] dstBuffer = new byte[dstWidth];
    int jj;
    int index;
    try {
        for (int j = 0; j < srcHeight; j++) {
            iis.readFully(srcBuffer, 0, srcWidth);

            jj = j - srcRegionYOffset;
            if (jj % ySubsamplingFactor == 0) {
                jj /= ySubsamplingFactor;
                if ((jj >= 0) && (jj < dstHeight)) {
                    for (int i = 0; i < dstWidth; i++) {
                        index = srcRegionXOffset + i * xSubsamplingFactor;
                        dstBuffer[i] = srcBuffer[index];
                    }
                    raster.setDataElements(0, jj, dstWidth, 1, dstBuffer);
                }
            }
        }
    } catch (IOException e) {
        bimage = null;
    }
    return bimage;
}

From source file:imageviewer.system.ImageViewerClient.java

private void initialize(CommandLine args) {

    // First, process all the different command line arguments that we
    // need to override and/or send onwards for initialization.

    boolean fullScreen = (args.hasOption("fullscreen")) ? true : false;
    String dir = (args.hasOption("dir")) ? args.getOptionValue("dir") : null;
    String type = (args.hasOption("type")) ? args.getOptionValue("type") : "DICOM";
    String prefix = (args.hasOption("client")) ? args.getOptionValue("client") : null;

    LOG.info("Java home environment: " + System.getProperty("java.home"));

    // Logging system taken care of through properties file.  Check
    // for JAI.  Set up JAI accordingly with the size of the cache
    // tile and to recycle cached tiles as needed.

    verifyJAI();//from  w w  w.j  a  va 2s.c om
    TileCache tc = JAI.getDefaultInstance().getTileCache();
    tc.setMemoryCapacity(32 * 1024 * 1024);
    TileScheduler ts = JAI.createTileScheduler();
    ts.setPriority(Thread.MAX_PRIORITY);
    JAI.getDefaultInstance().setTileScheduler(ts);
    JAI.getDefaultInstance().setRenderingHint(JAI.KEY_CACHED_TILE_RECYCLING_ENABLED, Boolean.TRUE);

    // Set up the frame and everything else.  First, try and set the
    // UI manager to use our look and feel because it's groovy and
    // lets us control the GUI components much better.

    try {
        UIManager.setLookAndFeel(new ImageViewerLookAndFeel());
        LookAndFeelAddons.setAddon(ImageViewerLookAndFeelAddons.class);
    } catch (Exception exc) {
        LOG.error("Could not set imageViewer L&F.");
    }

    // Load up the ApplicationContext information...

    ApplicationContext ac = ApplicationContext.getContext();
    if (ac == null) {
        LOG.error("Could not load configuration, exiting.");
        System.exit(1);
    }

    // Override the client node information based on command line
    // arguments...Make sure that the files are there, otherwise just
    // default to a local configuration.

    String hostname = new String("localhost");
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (Exception exc) {
    }

    String[] gatewayConfigs = (prefix != null)
            ? (new String[] { "resources/server/" + prefix + "GatewayConfig.xml",
                    (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                    "resources/server/" + hostname + "GatewayConfig.xml",
                    "resources/server/localGatewayConfig.xml" })
            : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                    "resources/server/" + hostname + "GatewayConfig.xml",
                    "resources/server/localGatewayConfig.xml" });
    String[] nodeConfigs = (prefix != null)
            ? (new String[] { "resources/server/" + prefix + "NodeConfig.xml",
                    (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                    "resources/server/" + hostname + "NodeConfig.xml", "resources/server/localNodeConfig.xml" })
            : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                    "resources/server/" + hostname + "NodeConfig.xml",
                    "resources/server/localNodeConfig.xml" });

    for (int loop = 0; loop < gatewayConfigs.length; loop++) {
        String s = gatewayConfigs[loop];
        if ((s != null) && (s.length() != 0) && (!"null".equals(s))) {
            File f = new File(s);
            if (f.exists()) {
                ac.setProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG, s);
                break;
            }
        }
    }

    LOG.info("Using gateway config: " + ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG));

    for (int loop = 0; loop < nodeConfigs.length; loop++) {
        String s = nodeConfigs[loop];
        if ((s != null) && (s.length() != 0) && (!"null".equals(s))) {
            File f = new File(s);
            if (f.exists()) {
                ac.setProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE, s);
                break;
            }
        }
    }
    LOG.info("Using client config: " + ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE));

    // Load the layouts and set the default window/level manager...

    LayoutFactory.initialize();
    DefaultWindowLevelManager dwlm = new DefaultWindowLevelManager();

    // Create the main JFrame, set its behavior, and let the
    // ApplicationPanel know the glassPane and layeredPane.  Set the
    // menubar based on reading in the configuration menus.

    mainFrame = new JFrame("imageviewer");
    try {
        ArrayList<Image> iconList = new ArrayList<Image>();
        iconList.add(ImageIO.read(new File("resources/icons/mii.png")));
        iconList.add(ImageIO.read(new File("resources/icons/mii32.png")));
        mainFrame.setIconImages(iconList);
    } catch (Exception exc) {
    }

    mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    mainFrame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            int confirm = ApplicationPanel.getInstance().showDialog(
                    "Are you sure you want to quit imageViewer?", null, JOptionPane.QUESTION_MESSAGE,
                    JOptionPane.OK_CANCEL_OPTION, UIManager.getIcon("Dialog.shutdownIcon"));
            if (confirm == JOptionPane.OK_OPTION) {
                boolean hasUnsaved = SaveStack.getInstance().hasUnsavedItems();
                if (hasUnsaved) {
                    int saveResult = ApplicationPanel.getInstance().showDialog(
                            "There is still unsaved data.  Do you want to save this data in the local archive?",
                            null, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
                    if (saveResult == JOptionPane.CANCEL_OPTION)
                        return;
                    if (saveResult == JOptionPane.YES_OPTION)
                        SaveStack.getInstance().saveAll();
                }
                LOG.info("Shutting down imageServer local archive...");
                try {
                    ImageViewerClientNode.getInstance().shutdown();
                } catch (Exception exc) {
                    LOG.error("Problem shutting down imageServer local archive...");
                } finally {
                    System.exit(0);
                }
            }
        }
    });

    String menuFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_MENUS);
    String ribbonFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_RIBBON);
    if (menuFile != null) {
        JMenuBar mb = new JMenuBar();
        mb.setBackground(Color.black);
        MenuReader.parseFile(menuFile, mb);
        mainFrame.setJMenuBar(mb);
        ApplicationContext.getContext().setApplicationMenuBar(mb);
    } else if (ribbonFile != null) {
        RibbonReader rr = new RibbonReader();
        JRibbon jr = rr.parseFile(ribbonFile);
        mainFrame.getContentPane().add(jr, BorderLayout.NORTH);
        ApplicationContext.getContext().setApplicationRibbon(jr);
    }
    mainFrame.getContentPane().add(ApplicationPanel.getInstance(), BorderLayout.CENTER);
    ApplicationPanel.getInstance().setGlassPane((JPanel) (mainFrame.getGlassPane()));
    ApplicationPanel.getInstance().setLayeredPane(mainFrame.getLayeredPane());

    // Load specified plugins...has to occur after the menus are
    // created, btw.

    PluginLoader.initialize("config/plugins.xml");

    // Detect operating system...

    String osName = System.getProperty("os.name");
    ApplicationContext.getContext().setProperty(ApplicationContext.OS_NAME, osName);
    LOG.info("Detected operating system: " + osName);

    // Try and hack the searched library paths if it's windows so we
    // can add a local dll path...

    try {
        if (osName.contains("Windows")) {
            Field f = ClassLoader.class.getDeclaredField("usr_paths");
            f.setAccessible(true);
            String[] paths = (String[]) f.get(null);
            String[] tmp = new String[paths.length + 1];
            System.arraycopy(paths, 0, tmp, 0, paths.length);
            File currentPath = new File(".");
            tmp[paths.length] = currentPath.getCanonicalPath() + "/lib/dll/";
            f.set(null, tmp);
            f.setAccessible(false);
        }
    } catch (Exception exc) {
        LOG.error("Error attempting to dynamically set library paths.");
    }

    // Get screen resolution...

    GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration();
    Rectangle r = gc.getBounds();
    LOG.info("Detected screen resolution: " + (int) r.getWidth() + "x" + (int) r.getHeight());

    // Try and see if Java3D is installed, and if so, what version...

    try {
        VirtualUniverse vu = new VirtualUniverse();
        Map m = vu.getProperties();
        String s = (String) m.get("j3d.version");
        LOG.info("Detected Java3D version: " + s);
    } catch (Throwable t) {
        LOG.info("Unable to detect Java3D installation");
    }

    // Try and see if native JOGL is installed...

    try {
        System.loadLibrary("jogl");
        ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.TRUE);
        LOG.info("Detected native libraries for JOGL");
    } catch (Throwable t) {
        LOG.info("Unable to detect native JOGL installation");
        ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.FALSE);
    }

    // Start the local client node to connect to the network and the
    // local archive running on this machine...Thread the connection
    // process so it doesn't block the imageViewerClient creating this
    // instance.  We may not be connected to the given gateway, so the
    // socketServer may go blah...

    final boolean useNetwork = (args.hasOption("nonet")) ? false : true;
    ApplicationPanel.getInstance().addStatusMessage("ImageViewer is starting up, please wait...");
    if (useNetwork)
        LOG.info("Starting imageServer client to join network - please wait...");
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                ImageViewerClientNode.getInstance(
                        (String) ApplicationContext.getContext()
                                .getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                        (String) ApplicationContext.getContext()
                                .getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                        useNetwork);
                ApplicationPanel.getInstance().addStatusMessage("Ready");
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    });
    t.setPriority(9);
    t.start();

    this.fullScreen = fullScreen;
    mainFrame.setUndecorated(fullScreen);

    // Set the view to encompass the default screen.

    if (fullScreen) {
        Insets i = Toolkit.getDefaultToolkit().getScreenInsets(gc);
        mainFrame.setLocation(r.x + i.left, r.y + i.top);
        mainFrame.setSize(r.width - i.left - i.right, r.height - i.top - i.bottom);
    } else {
        mainFrame.setSize(1100, 800);
        mainFrame.setLocation(r.x + 200, r.y + 100);
    }

    if (dir != null)
        ApplicationPanel.getInstance().load(dir, type);

    timer = new Timer();
    timer.schedule(new GarbageCollectionTimer(), 5000, 2500);
    mainFrame.setVisible(true);
}

From source file:fr.avianey.androidsvgdrawable.SvgDrawablePlugin.java

/**
 * Given it's bounds, transcodes a svg file to a raster image for the desired density
 * @param svg/*from   w  w  w.  j a va 2 s  .co  m*/
 * @param targetDensity 
 * @param bounds
 * @param destination
 * @throws IOException
 * @throws TranscoderException
 * @throws IllegalAccessException 
 * @throws InstantiationException 
 */
@VisibleForTesting
void transcode(QualifiedResource svg, Density targetDensity, Rectangle bounds, File destination,
        NinePatch ninePatch)
        throws IOException, TranscoderException, InstantiationException, IllegalAccessException {
    transcode(svg, targetDensity, destination,
            new Float(bounds.getWidth() * svg.getDensity().ratio(targetDensity)),
            new Float(bounds.getHeight() * svg.getDensity().ratio(targetDensity)), ninePatch);
}

From source file:fr.avianey.androidsvgdrawable.SvgDrawablePlugin.java

public void execute() {
    // validating target densities specified in pom.xml
    // untargetted densities will be ignored except for the fallback density if specified
    final Set<Density> targetDensities = new HashSet<>(Arrays.asList(parameters.getTargetedDensities()));
    if (targetDensities.isEmpty()) {
        targetDensities.addAll(EnumSet.allOf(Density.class));
    }/*w w  w.  j  a  v  a 2s .c om*/
    getLog().info("Targeted densities : " + Joiner.on(", ").join(targetDensities));

    /********************************
     * Load NinePatch configuration *
     ********************************/

    NinePatchMap ninePatchMap = new NinePatchMap();
    if (parameters.getNinePatchConfig() != null && parameters.getNinePatchConfig().isFile()) {
        getLog().info(
                "Loading NinePatch configuration file " + parameters.getNinePatchConfig().getAbsolutePath());
        try (final Reader reader = new FileReader(parameters.getNinePatchConfig())) {
            Type t = new TypeToken<Set<NinePatch>>() {
            }.getType();
            Set<NinePatch> ninePathSet = (Set<NinePatch>) (new GsonBuilder().create().fromJson(reader, t));
            ninePatchMap = NinePatch.init(ninePathSet);
        } catch (IOException e) {
            getLog().error(e);
        }
    } else {
        getLog().info("No NinePatch configuration file specified");
    }

    /*****************************
     * List input svg to convert *
     *****************************/

    getLog().info("Listing SVG files in " + parameters.getFrom().getAbsolutePath());
    final Collection<QualifiedResource> svgToConvert = listQualifiedResources(parameters.getFrom(), "svg");
    getLog().info("SVG files : " + Joiner.on(", ").join(svgToConvert));

    /*****************************
     * List input svgmask to use *
     *****************************/

    File svgMaskDirectory = parameters.getSvgMaskDirectory();
    File svgMaskResourcesDirectory = parameters.getSvgMaskResourcesDirectory();
    if (svgMaskDirectory == null) {
        svgMaskDirectory = parameters.getFrom();
    }
    if (svgMaskResourcesDirectory == null) {
        svgMaskResourcesDirectory = svgMaskDirectory;
    }
    getLog().info("Listing SVGMASK files in " + svgMaskDirectory.getAbsolutePath());
    final Collection<QualifiedResource> svgMasks = listQualifiedResources(svgMaskDirectory, "svgmask");
    final Collection<QualifiedResource> svgMaskResources = new ArrayList<>();
    getLog().info("SVGMASK files : " + Joiner.on(", ").join(svgMasks));
    if (!svgMasks.isEmpty()) {
        // list masked resources
        if (svgMaskResourcesDirectory.equals(parameters.getFrom())) {
            svgMaskResources.addAll(svgToConvert);
        } else {
            svgMaskResources.addAll(listQualifiedResources(svgMaskResourcesDirectory, "svg"));
        }
        getLog().info("SVG files to mask : " + Joiner.on(", ").join(svgMaskResources));
        // generate masked svg
        for (QualifiedResource maskFile : svgMasks) {
            getLog().info("Generating masked files for " + maskFile);
            try {
                Collection<QualifiedResource> generatedResources = new SvgMask(maskFile)
                        .generatesMaskedResources(parameters.getSvgMaskedSvgOutputDirectory(), svgMaskResources,
                                parameters.isUseSameSvgOnlyOnceInMask(), parameters.getOverrideMode());
                getLog().debug("+ " + Joiner.on(", ").join(generatedResources));
                svgToConvert.addAll(generatedResources);
            } catch (XPathExpressionException | TransformerException | ParserConfigurationException
                    | SAXException | IOException e) {
                getLog().error(e);
            }
        }
    } else {
        getLog().info("No SVGMASK file found.");
    }

    QualifiedResource highResIcon = null;

    /*********************************
     * Create svg in res/* folder(s) *
     *********************************/

    for (QualifiedResource svg : svgToConvert) {
        try {
            getLog().info(
                    "Transcoding " + FilenameUtils.getName(svg.getAbsolutePath()) + " to targeted densities");
            Rectangle bounds = extractSVGBounds(svg);
            if (getLog().isDebugEnabled()) {
                getLog().debug("+ source dimensions [width=" + bounds.getWidth() + " - height="
                        + bounds.getHeight() + "]");
            }
            if (parameters.getHighResIcon() != null && parameters.getHighResIcon().equals(svg.getName())) {
                highResIcon = svg;
            }
            // for each target density :
            // - find matching destinations :
            //   - matches all extra qualifiers
            //   - no other output with a qualifiers set that is a subset of this output
            // - if no match, create required directories
            for (Density d : targetDensities) {
                NinePatch ninePatch = ninePatchMap.getBestMatch(svg);
                File destination = svg.getOutputFor(d, parameters.getTo(),
                        ninePatch == null ? parameters.getOutputType() : OutputType.drawable);
                if (!destination.exists() && parameters.isCreateMissingDirectories()) {
                    destination.mkdirs();
                }
                if (destination.exists()) {
                    getLog().debug("Transcoding " + svg.getName() + " to " + destination.getName());
                    transcode(svg, d, bounds, destination, ninePatch);
                } else {
                    getLog().info("Qualified output " + destination.getName() + " does not exists. "
                            + "Set 'createMissingDirectories' to true if you want it to be created if missing...");
                }
            }
        } catch (IOException | TranscoderException | InstantiationException | IllegalAccessException e) {
            getLog().error("Error while converting " + svg, e);
        }
    }

    /******************************************
     * Generates the play store high res icon *
     ******************************************/

    if (highResIcon != null) {
        try {
            // TODO : add a garbage density (NO_DENSITY) for the highResIcon
            // TODO : make highResIcon size configurable
            // TODO : generates other play store assets
            // TODO : parameterized SIZE
            getLog().info("Generating high resolution icon");
            transcode(highResIcon, Density.mdpi, new File("."), 512, 512, null);
        } catch (IOException | TranscoderException | InstantiationException | IllegalAccessException e) {
            getLog().error("Error while converting " + highResIcon, e);
        }
    }
}

From source file:liveDriftCorrectionGUI.java

private LMA fitRois(float[][] imgData, Roi iRois, double[] InitParam) {
    Rectangle rec_ = iRois.getBounds();
    double[][] img;
    img = new double[(int) rec_.getWidth()][(int) rec_.getHeight()];
    for (int iCol = (int) rec_.getX(); iCol < rec_.getX() + rec_.getWidth(); iCol++) {
        for (int iRow = (int) rec_.getY(); iRow < rec_.getY() + rec_.getHeight(); iRow++) {
            int cX = iCol - (int) rec_.getX();
            int cY = iRow - (int) rec_.getY();
            //ReportingUtils.showMessage(Float.toString(imgData[iCol][iRow]));
            img[cX][cY] = (double) imgData[iCol][iRow];
        }//from ww w  .  j a v a 2 s.c  o  m
    }
    double[][] InitConbineData;
    InitConbineData = LM2DGaussFit.GenerateDataPoint((int) rec_.getWidth(), (int) rec_.getHeight(), img);
    LMA lma = new LMA(new LM2DGaussFit.LM2DGaussFunction(), InitParam, InitConbineData);
    lma.maxIterations = 100;
    lma.fit();
    return lma;
}