Java Code Examples for java.awt.Rectangle.intersection()

The following are Jave code examples for showing how to use intersection() of the java.awt.Rectangle class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: VASSAL-src   File: SetupStack.java   View Source Code Vote up 6 votes
public void scrollAtEdge(Point evtPt, int dist) {
  JScrollPane scroll = myStack.stackConfigurer.getScroll();

  Point p = new Point(evtPt.x - scroll.getViewport().getViewPosition().x,
      evtPt.y - scroll.getViewport().getViewPosition().y);
  int dx = 0, dy = 0;
  if (p.x < dist && p.x >= 0)
    dx = -1;
  if (p.x >= scroll.getViewport().getSize().width - dist
      && p.x < scroll.getViewport().getSize().width)
    dx = 1;
  if (p.y < dist && p.y >= 0)
    dy = -1;
  if (p.y >= scroll.getViewport().getSize().height - dist
      && p.y < scroll.getViewport().getSize().height)
    dy = 1;

  if (dx != 0 || dy != 0) {
    Rectangle r = new Rectangle(scroll.getViewport().getViewRect());
    r.translate(2 * dist * dx, 2 * dist * dy);
    r = r.intersection(new Rectangle(new Point(0, 0), getPreferredSize()));
    scrollRectToVisible(r);
  }
}
 
Example 2
Project: Tarski   File: EditorPalette.java   View Source Code Vote up 6 votes
/**
 * 
 */
public void paintComponent(Graphics g) {
  if (gradientColor == null) {
    super.paintComponent(g);
  } else {
    Rectangle rect = getVisibleRect();

    if (g.getClipBounds() != null) {
      rect = rect.intersection(g.getClipBounds());
    }

    Graphics2D g2 = (Graphics2D) g;

    g2.setPaint(new GradientPaint(0, 0, getBackground(), getWidth(), 0, gradientColor));
    g2.fill(rect);
  }
}
 
Example 3
Project: openjdk-jdk10   File: ImageReader.java   View Source Code Vote up 6 votes
/**
 * A utility method that may be used by readers to compute the
 * region of the source image that should be read, taking into
 * account any source region and subsampling offset settings in
 * the supplied {@code ImageReadParam}.  The actual
 * subsampling factors, destination size, and destination offset
 * are <em>not</em> taken into consideration, thus further
 * clipping must take place.  The {@link #computeRegions computeRegions}
 * method performs all necessary clipping.
 *
 * @param param the {@code ImageReadParam} being used, or
 * {@code null}.
 * @param srcWidth the width of the source image.
 * @param srcHeight the height of the source image.
 *
 * @return the source region as a {@code Rectangle}.
 */
protected static Rectangle getSourceRegion(ImageReadParam param,
                                           int srcWidth,
                                           int srcHeight) {
    Rectangle sourceRegion = new Rectangle(0, 0, srcWidth, srcHeight);
    if (param != null) {
        Rectangle region = param.getSourceRegion();
        if (region != null) {
            sourceRegion = sourceRegion.intersection(region);
        }

        int subsampleXOffset = param.getSubsamplingXOffset();
        int subsampleYOffset = param.getSubsamplingYOffset();
        sourceRegion.x += subsampleXOffset;
        sourceRegion.y += subsampleYOffset;
        sourceRegion.width -= subsampleXOffset;
        sourceRegion.height -= subsampleYOffset;
    }

    return sourceRegion;
}
 
Example 4
Project: sumo   File: GDALSentinel1.java   View Source Code Vote up 6 votes
/**
 * 
 * @param x
 * @param y
 * @param width
 * @param height
 * @param band
 * @return
 */
public synchronized int[] read(int x, int y,int w,int h, int band) {
    Rectangle rect = new Rectangle(x, y, w, h);
    rect = rect.intersection(getImage(band).getBounds());
    int data[]=null;

    GeoToolsGDALReader tiff=(GeoToolsGDALReader)getImage(band);
     try {
 		int[] b=tiff.readPixValues(x, y, w,h);
 		data=new int[b.length];
     	for(int i=0;i<b.length;i++)
     		data[i]=b[i];
 		
     } catch (Exception ex) {
         logger.warn(ex.getMessage());
     }finally{
     }
    
    return data;
}
 
Example 5
Project: geomapapp   File: JPEGimage.java   View Source Code Vote up 6 votes
public Rectangle getImageableRect(Rectangle rect, int xAvg, int yAvg,
		int xRep, int yRep) {
	Rectangle r = rect.intersection(new Rectangle(0,0,width*xRep/xAvg,height*yRep/yAvg));
	if(flip==hFlip && xA==xAvg && yA== yAvg && xRep==xR && yRep==yR 
			&& tmpRect != null && tmpRect.contains(r))return tmpRect;
	if(r.width<=0 || r.height <=0) return r;
	int x = r.x + r.width;
	int dx = x % (xRep*4);
	if( dx != 0 ) x += xRep*4-dx;
	r.x -= r.x % (xRep*4);
	r.width = x - r.x;
	int y = r.y + r.height;
	int dy = y % yRep;
	if( dy != 0 ) y += yRep-dy;
	r.y -= r.y % yRep;
	r.height = y - r.y;
	return r;
}
 
Example 6
Project: sumo   File: AlosGeoTiff.java   View Source Code Vote up 6 votes
/**
*
* @param x
* @param y
* @param width
* @param height
* @param band
* @return
*/
public int[] read(int x, int y,int w,int h, int band) {
    Rectangle rect = new Rectangle(x, y, w, h);
    rect = rect.intersection(getImage(band).getBounds());
    int data[]=null;

     TIFF tiff=getImage(band);
     try {
     	BufferedImage bi=null;
 		bi=tiff.read(0, rect);
 		DataBufferUShort raster=(DataBufferUShort)bi.getRaster().getDataBuffer();
 		short[] b=raster.getData();
 		data=new int[b.length];
     	for(int i=0;i<b.length;i++)
     		data[i]=b[i];

     } catch (Exception ex) {
         logger.warn(ex.getMessage());
     }finally{
     }

    return data;
}
 
Example 7
Project: OpenJSharp   File: BufferedImage.java   View Source Code Vote up 5 votes
/**
 * Sets a rectangular region of the image to the contents of the
 * specified <code>Raster</code> <code>r</code>, which is
 * assumed to be in the same coordinate space as the
 * <code>BufferedImage</code>. The operation is clipped to the bounds
 * of the <code>BufferedImage</code>.
 * @param r the specified <code>Raster</code>
 * @see #getData
 * @see #getData(Rectangle)
*/
public void setData(Raster r) {
    bitmap2Raster();
    this.currentBuffer = BUFFER_RASTER;
    
    int width = r.getWidth();
    int height = r.getHeight();
    int startX = r.getMinX();
    int startY = r.getMinY();

    int[] tdata = null;

    // Clip to the current Raster
    Rectangle rclip = new Rectangle(startX, startY, width, height);
    Rectangle bclip = new Rectangle(0, 0, raster.width, raster.height);
    Rectangle intersect = rclip.intersection(bclip);
    if (intersect.isEmpty()) {
        return;
    }
    width = intersect.width;
    height = intersect.height;
    startX = intersect.x;
    startY = intersect.y;

    // remind use get/setDataElements for speed if Rasters are
    // compatible
    for (int i = startY; i < startY+height; i++)  {
        tdata = r.getPixels(startX,i,width,1,tdata);
        raster.setPixels(startX,i,width,1, tdata);
    }
}
 
Example 8
Project: incubator-netbeans   File: ProfilerTableHovers.java   View Source Code Vote up 5 votes
private Rectangle[] computePopups(int row, int column, Point point, Component renderer) {
    Rectangle rendererRect = getRendererRect(column, renderer);
    if (rendererRect == null) return null;
    
    Rectangle cellRect = table.getCellRect(row, column, true);
    rendererRect.translate(cellRect.x, cellRect.y);
    cellRect.width -= 1;
    if (cellRect.contains(rendererRect)) return null; // Value fully visible
    
    Rectangle visibleRect = cellRect.intersection(rendererRect);
    if (!visibleRect.contains(point)) return null; // Value fully invisible
    
    // Mouse over partially visible value
    Rectangle[] ret = new Rectangle[2];
    
    if (rendererRect.x < visibleRect.x) {
        Rectangle left = new Rectangle(rendererRect);
        left.width = visibleRect.x - left.x;
        ret[POPUP_LEFT] = left;
    }

    // rendererRect.x + rendererRect.width *- 1*: workaround for extra space for correctly right-aligned values
    if (rendererRect.x + rendererRect.width - 1 > visibleRect.x + visibleRect.width) {
        Rectangle right = new Rectangle(rendererRect);
        right.x = visibleRect.x + visibleRect.width;
        right.width = rendererRect.x + rendererRect.width - right.x;
        ret[POPUP_RIGHT] = right;
    }
    
    return ret;
}
 
Example 9
Project: sumo   File: Radarsat2Image_SLC.java   View Source Code Vote up 5 votes
@Override
public int[] readTile(int x, int y, int width, int height,int band) {

    Rectangle rect = new Rectangle(x, y, width, height);
    rect = rect.intersection(bounds);
    int[] tile = new int[height * width];
    if (rect.isEmpty()) {
        return tile;
    }
    if (rect.y != preloadedInterval[0] | rect.y + rect.height != preloadedInterval[1]) {
        preloadLineTile(rect.y, rect.height,band);
    }
    int yOffset =  getImage(band).getxSize();
    int xinit = rect.x - x;
    int yinit = rect.y - y;
    int temp =0;
    try{
     for (int i = 0; i < rect.height; i++) {
         for (int j = 0; j < rect.width; j++) {
             temp = (i * yOffset + j + rect.x);
             long real=preloadedDataReal[temp];
             long img=preloadedDataImg[temp];
             tile[(i + yinit) * width + j + xinit] = (int)Math.sqrt(real*real+img*img);
         }
     }
    }catch(Exception e ){
    	e.printStackTrace();
    }    
    return tile;
}
 
Example 10
Project: sumo   File: Radarsat2Image.java   View Source Code Vote up 5 votes
@Override
public int[] readTile(int x, int y, int width, int height,int band) {
    Rectangle rect = new Rectangle(x, y, width, height);
    rect = rect.intersection(bounds);
    int[] tile= new int[height*width];
    if (rect.isEmpty()) {
        return tile;
    }
    if (rect.y != preloadedInterval[0] | rect.y + rect.height != preloadedInterval[1]) {
        preloadLineTile(rect.y, rect.height,band);
    }
    int yOffset = getImage(band).getxSize();
    int xinit = rect.x - x;
    int yinit = rect.y - y;
    for (int i = 0; i < rect.height; i++) {
        for (int j = 0; j < rect.width; j++) {
            int temp = i * yOffset + j + rect.x;
            	if(preloadedData.length>=temp){
            		tile[(i + yinit) * width + j + xinit] = preloadedData[temp];
            	}else{
            		
                	//logger.debug("");
            	}	
        }
    }
    return tile;
}
 
Example 11
Project: sumo   File: Alos.java   View Source Code Vote up 5 votes
@Override
public int[] readTile(int x, int y, int width, int height, int band) {
	TIFF tiff=(TIFF)getImage(band);

	Rectangle rect = new Rectangle(x, y, width, height);
       rect = rect.intersection(tiff.getBounds());

       int[] tile = new int[height * width];
       if (rect.isEmpty()) {
           return tile;
       }

       if (rect.y != preloadedInterval[0] || rect.y + rect.height != preloadedInterval[1]||preloadedData.length<(rect.width*rect.height-1)) {
           preloadLineTile(rect.y, rect.height,band);
       }else{
       	logger.debug("using preloaded data");
       }

       int yOffset = tiff.xSize;
       int xinit = rect.x - x;
       int yinit = rect.y - y;
       for (int i = 0; i < rect.height; i++) {
           for (int j = 0; j < rect.width; j++) {
               int temp = i * yOffset + j + rect.x;
               try{
               	tile[(i + yinit) * width + j + xinit] =(int) preloadedData[temp];
               }catch(ArrayIndexOutOfBoundsException e ){
               	logger.warn("readTile function:"+e.getMessage());
               }
           }
           }
       return tile;
}
 
Example 12
Project: sumo   File: GDALAlosCeos.java   View Source Code Vote up 5 votes
@Override
public long readPixel(int x, int y, int band) {
	Rectangle rect = new Rectangle(x, y, 1, 1);
	rect = rect.intersection(getImage(band).getBounds());
	int data[] = null;

	GeoToolsGDALReader img = (GeoToolsGDALReader)getImage(band);
	try {
		data=img.readPixValues(x, y,1,1);
	} finally {
	}

	return data[0];

}
 
Example 13
Project: incubator-netbeans   File: TransformableCanvasComponent.java   View Source Code Vote up 4 votes
protected final void paintComponent(Graphics g, Rectangle invalidArea) {
    int shiftX = 0;
    int shiftY = 0;

    contentsWillBeUpdated(offsetX, offsetY, scaleX, scaleY,
                          lastOffsetX, lastOffsetY, lastScaleX, lastScaleY);

    if (!translationPending()) {
        // No translation
        paintContents(g, invalidArea);
    } else {
        // Translation
        int width = getWidth();
        int height = getHeight();

        if (Math.abs(dx) >= width || Math.abs(dy) >= height) {
            // Translation outside of visible area
            paintContents(g, new Rectangle(0, 0, width, height));
        } else {
            // Translation in visible area
            int idx = rightBased ? -(int)dx : (int)dx;
            int idy = bottomBased ? -(int)dy : (int)dy;

            // Total component area
            int total = width * height;
            // Area of the contents saved by shift
            int shiftedSaved = (width - Math.abs(idx)) * (height - Math.abs(idy));

            if (idx != 0 && idy != 0 && shiftedSaved < total * DIAGONAL_SHIFT_ACCEL_LIMIT) {
                // DIAGONAL_SHIFT_ACCEL_LIMIT not met for diagonal shift
                paintContents(g, new Rectangle(0, 0, width, height));
            } else {
                // Saved rectangle
                Rectangle viewport = new Rectangle(idx, idy, width, height);
                Rectangle savedRect = viewport.intersection(
                        new Rectangle(0, 0, width, height));

                // InvalidArea to repaint
                Rectangle invalidRect = invalidArea.intersection(savedRect);

                // Area of invalidRect
                int invalidAfterShift = invalidRect.isEmpty() ? 0 :
                                     invalidRect.width * invalidRect.height;

                // Total saved area
                int savedTotal = shiftedSaved - invalidAfterShift;

                if (savedTotal < total * SHIFT_ACCEL_LIMIT) {
                    // SHIFT_ACCEL_LIMIT not met for shift
                    paintContents(g, new Rectangle(0, 0, width, height));
                } else {
                    // Shift
                    shift(g, idx, idy, width, height);

                    // Repaint original invalidArea if needed
                    if (invalidAfterShift != 0) paintContents(g, invalidRect);

                    shiftX = idx;
                    shiftY = idy;
                }
            }
        }
    }

    contentsUpdated(offsetX, offsetY, scaleX, scaleY, lastOffsetX, lastOffsetY,
                    lastScaleX, lastScaleY, shiftX, shiftY);

    dx = 0;
    dy = 0;
    lastOffsetX = offsetX;
    lastOffsetY = offsetY;
    lastScaleX = scaleX;
    lastScaleY = scaleY;
}
 
Example 14
Project: openjdk-jdk10   File: SimpleRenderedImage.java   View Source Code Vote up 4 votes
/**
 * Copies an arbitrary rectangular region of the RenderedImage
 * into a caller-supplied WritableRaster.  The region to be
 * computed is determined by clipping the bounds of the supplied
 * WritableRaster against the bounds of the image.  The supplied
 * WritableRaster must have a SampleModel that is compatible with
 * that of the image.
 *
 * <p> If the raster argument is null, the entire image will
 * be copied into a newly-created WritableRaster with a SampleModel
 * that is compatible with that of the image.
 *
 * @param dest a WritableRaster to hold the returned portion of
 *        the image.
 * @return a reference to the supplied WritableRaster, or to a
 *         new WritableRaster if the supplied one was null.
 */
public WritableRaster copyData(WritableRaster dest) {
    // Get the image bounds.
    Rectangle imageBounds = getBounds();

    Rectangle bounds;
    if (dest == null) {
        // Create a WritableRaster for the entire image.
        bounds = imageBounds;
        Point p = new Point(minX, minY);
        SampleModel sm =
            sampleModel.createCompatibleSampleModel(width, height);
        dest = Raster.createWritableRaster(sm, p);
    } else {
        bounds = dest.getBounds();
    }

    // Determine tile limits for the intersection of the prescribed
    // bounds with the image bounds.
    Rectangle xsect = imageBounds.contains(bounds) ?
        bounds : bounds.intersection(imageBounds);
    int startX = XToTileX(xsect.x);
    int startY = YToTileY(xsect.y);
    int endX = XToTileX(xsect.x + xsect.width - 1);
    int endY = YToTileY(xsect.y + xsect.height - 1);

    // Loop over the tiles in the intersection.
    for (int j = startY; j <= endY; j++) {
        for (int i = startX; i <= endX; i++) {
            // Retrieve the tile.
            Raster tile = getTile(i, j);

            // Create a child of the tile for the intersection of
            // the tile bounds and the bounds of the requested area.
            Rectangle tileRect = tile.getBounds();
            Rectangle intersectRect =
                bounds.intersection(tile.getBounds());
            Raster liveRaster = tile.createChild(intersectRect.x,
                                                 intersectRect.y,
                                                 intersectRect.width,
                                                 intersectRect.height,
                                                 intersectRect.x,
                                                 intersectRect.y,
                                                 null);

            // Copy the data from the child.
            dest.setRect(liveRaster);
        }
    }

    return dest;
}
 
Example 15
Project: VASSAL-src   File: Region.java   View Source Code Vote up 4 votes
public void draw(Graphics g, Rectangle bounds, Rectangle visibleRect, double scale, boolean reversed, int xOffset, int yOffset) {
  if (!bounds.intersects(visibleRect)) {
    return;
  }

  final int labelOffset = 7;

  int size = (int) (scale * myGrid.getFontSize() + 0.5);
  Font f = new Font("Dialog", Font.PLAIN, size); //$NON-NLS-1$

  Color fg = selected ? Color.white : Color.black;
  Color bg = selected ? Color.black : Color.white;

  Rectangle region = bounds.intersection(visibleRect);

  Shape oldClip = g.getClip();
  if (oldClip != null) {
    Area clipArea = new Area(oldClip);
    clipArea.intersect(new Area(region));
    g.setClip(clipArea);
  }

  int posX = (int) (scale * origin.x + 0.5) + bounds.x - 1 + xOffset;
  int posY = (int) (scale * origin.y + 0.5) + bounds.y - 1 + yOffset;

  Color saveColor = g.getColor();

  g.setColor(bg);
  g.fillRect(posX, posY, 3, 3);
  g.setColor(fg);
  g.drawRect(posX, posY, 3, 3);

  g.setColor(saveColor);

  Labeler.drawLabel(g, getLocalizedConfigureName(), posX, posY + labelOffset, f, Labeler.CENTER,
                    Labeler.TOP, fg, bg, fg);
  g.setClip(oldClip);

  // Calculate and store the selection rectangle
  int width = g.getFontMetrics().stringWidth(getConfigureName() + "  ")+1; //$NON-NLS-1$
  int height = g.getFontMetrics().getHeight()+1;

  selectionRect.setLocation(posX - (width / 2), posY - 1);
  selectionRect.setSize(width, height + labelOffset + 1);

}
 
Example 16
Project: jdk8u-jdk   File: SourceClippingBlitTest.java   View Source Code Vote up 4 votes
public void test(Rectangle srcRect, Rectangle dstRect) {
    int w = getWidth();
    int h = getHeight();
    Toolkit.getDefaultToolkit().sync();
    try {
        Thread.sleep(2000);
    } catch (InterruptedException ex) {}
    Point p = getLocationOnScreen();
    grabbedBI = robot.createScreenCapture(new Rectangle(p.x, p.y, w, h));

    // calculate the destination rectangle
    Rectangle srcBounds = srcRect.intersection(IMAGE_BOUNDS);
    int trX = dstRect.x - srcRect.x;
    int trY = dstRect.y - srcRect.y;
    Rectangle newDstRect = (Rectangle)dstRect.clone();
    newDstRect.translate(-trX, -trY);
    Rectangle.intersect(newDstRect, srcBounds, newDstRect);
    newDstRect.translate(trX, trY);
    Rectangle.intersect(newDstRect, new Rectangle(0, 0, w, h), newDstRect);

    System.out.println("calculated dest rect:" + newDstRect);

    // we do implicit clipping of the destination surface
    // by only checking pixels within its bounds
    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            int rgb = 0;
            if (newDstRect.contains(x, y)) {
                rgb = Color.red.getRGB();
            } else {
                rgb = Color.green.getRGB();
            }
            if (grabbedBI.getRGB(x, y) != rgb) {
                String msg1 = "Test failed at x="+x+" y="+y;
                System.out.println(msg1);
                System.out.println(" expected: "+Integer.toHexString(rgb)+
                        " got:"+Integer.toHexString(grabbedBI.getRGB(x, y)));
                throw new RuntimeException(msg1);
            }
        }
    }
    System.out.println("subtest passed");
}
 
Example 17
Project: VASSAL-src   File: SquareGrid.java   View Source Code Vote up 4 votes
/** Draw the grid even if not marked visible */
public void forceDraw(Graphics g, Rectangle bounds, Rectangle visibleRect, double scale, boolean reversed) {
  if (!bounds.intersects(visibleRect) || color == null) {
    return;
  }

  Graphics2D g2d = (Graphics2D) g;
  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                       RenderingHints.VALUE_ANTIALIAS_ON);

  Rectangle region = bounds.intersection(visibleRect);

  Shape oldClip = g2d.getClip();
  if (oldClip != null) {
    Area clipArea = new Area(oldClip);
    clipArea.intersect(new Area(region));
    g2d.setClip(clipArea);
  }

  double deltaX = scale * dx;
  double deltaY = scale * dy;

  double xmin = reversed ? bounds.x + scale * origin.x + bounds.width - deltaX * round((bounds.x + scale * origin.x + bounds.width - region.x) / deltaX) + deltaX / 2
      : bounds.x + scale * origin.x + deltaX * round((region.x - bounds.x - scale * origin.x) / deltaX) + deltaX / 2;
  double xmax = region.x + region.width;
  double ymin = reversed ? bounds.y + scale * origin.y + bounds.height - deltaY * round((bounds.y + scale * origin.y + bounds.height - region.y) / deltaY) + deltaY / 2
      : bounds.y + scale * origin.y + deltaY * round((region.y - bounds.y - scale * origin.y) / deltaY) + deltaY / 2;
  double ymax = region.y + region.height;

  Point p1 = new Point();
  Point p2 = new Point();
  g2d.setColor(color);
  // x is the location of a vertical line
  for (double x = xmin; x < xmax; x += deltaX) {
    p1.move((int) round(x), region.y);
    p2.move((int) round(x), region.y + region.height);
    g2d.drawLine(p1.x, p1.y, p2.x, p2.y);
  }
  for (double y = ymin; y < ymax; y += deltaY) {
    g2d.drawLine(region.x, (int) round(y), region.x + region.width, (int) round(y));
  }
  if (dotsVisible) {
    xmin = reversed ? bounds.x + scale * origin.x + bounds.width - deltaX * round((bounds.x + scale * origin.x + bounds.width - region.x) / deltaX)
        : bounds.x + scale * origin.x + deltaX * round((region.x - bounds.x - scale * origin.x) / deltaX);
    ymin = reversed ? bounds.y + scale * origin.y + bounds.height - deltaY * round((bounds.y + scale * origin.y + bounds.height - region.y) / deltaY)
        : bounds.y + scale * origin.y + deltaY * round((region.y - bounds.y - scale * origin.y) / deltaY);
    for (double x = xmin; x < xmax; x += deltaX) {
      for (double y = ymin; y < ymax; y += deltaY) {
        p1.move((int) round(x - 0.5), (int) round(y - 0.5));
        g2d.fillRect(p1.x, p1.y, 2, 2);
      }
    }
  }
  g2d.setClip(oldClip);
}
 
Example 18
Project: OpenJSharp   File: GIFImageWriter.java   View Source Code Vote up 4 votes
/**
 * Compute the source region and destination dimensions taking any
 * parameter settings into account.
 */
private static void computeRegions(Rectangle sourceBounds,
                                   Dimension destSize,
                                   ImageWriteParam p) {
    ImageWriteParam param;
    int periodX = 1;
    int periodY = 1;
    if (p != null) {
        int[] sourceBands = p.getSourceBands();
        if (sourceBands != null &&
            (sourceBands.length != 1 ||
             sourceBands[0] != 0)) {
            throw new IllegalArgumentException("Cannot sub-band image!");
        }

        // Get source region and subsampling factors
        Rectangle sourceRegion = p.getSourceRegion();
        if (sourceRegion != null) {
            // Clip to actual image bounds
            sourceRegion = sourceRegion.intersection(sourceBounds);
            sourceBounds.setBounds(sourceRegion);
        }

        // Adjust for subsampling offsets
        int gridX = p.getSubsamplingXOffset();
        int gridY = p.getSubsamplingYOffset();
        sourceBounds.x += gridX;
        sourceBounds.y += gridY;
        sourceBounds.width -= gridX;
        sourceBounds.height -= gridY;

        // Get subsampling factors
        periodX = p.getSourceXSubsampling();
        periodY = p.getSourceYSubsampling();
    }

    // Compute output dimensions
    destSize.setSize((sourceBounds.width + periodX - 1)/periodX,
                     (sourceBounds.height + periodY - 1)/periodY);
    if (destSize.width <= 0 || destSize.height <= 0) {
        throw new IllegalArgumentException("Empty source region!");
    }
}
 
Example 19
Project: jdk8u-jdk   File: SunGraphics2D.java   View Source Code Vote up 4 votes
/**
 * Returns a rectangle in image coordinates that may be required
 * in order to draw the given image into the given clipping region
 * through a pair of AffineTransforms.  In addition, horizontal and
 * vertical padding factors for antialising and interpolation may
 * be used.
 */
private static Rectangle getImageRegion(RenderedImage img,
                                        Region compClip,
                                        AffineTransform transform,
                                        AffineTransform xform,
                                        int padX, int padY) {
    Rectangle imageRect =
        new Rectangle(img.getMinX(), img.getMinY(),
                      img.getWidth(), img.getHeight());

    Rectangle result = null;
    try {
        double p[] = new double[8];
        p[0] = p[2] = compClip.getLoX();
        p[4] = p[6] = compClip.getHiX();
        p[1] = p[5] = compClip.getLoY();
        p[3] = p[7] = compClip.getHiY();

        // Inverse transform the output bounding rect
        transform.inverseTransform(p, 0, p, 0, 4);
        xform.inverseTransform(p, 0, p, 0, 4);

        // Determine a bounding box for the inverse transformed region
        double x0,x1,y0,y1;
        x0 = x1 = p[0];
        y0 = y1 = p[1];

        for (int i = 2; i < 8; ) {
            double pt = p[i++];
            if (pt < x0)  {
                x0 = pt;
            } else if (pt > x1) {
                x1 = pt;
            }
            pt = p[i++];
            if (pt < y0)  {
                y0 = pt;
            } else if (pt > y1) {
                y1 = pt;
            }
        }

        // This is padding for anti-aliasing and such.  It may
        // be more than is needed.
        int x = (int)x0 - padX;
        int w = (int)(x1 - x0 + 2*padX);
        int y = (int)y0 - padY;
        int h = (int)(y1 - y0 + 2*padY);

        Rectangle clipRect = new Rectangle(x,y,w,h);
        result = clipRect.intersection(imageRect);
    } catch (NoninvertibleTransformException nte) {
        // Worst case bounds are the bounds of the image.
        result = imageRect;
    }

    return result;
}
 
Example 20
Project: openjdk-jdk10   File: GIFImageWriter.java   View Source Code Vote up 4 votes
/**
 * Compute the source region and destination dimensions taking any
 * parameter settings into account.
 */
private static void computeRegions(Rectangle sourceBounds,
                                   Dimension destSize,
                                   ImageWriteParam p) {
    ImageWriteParam param;
    int periodX = 1;
    int periodY = 1;
    if (p != null) {
        int[] sourceBands = p.getSourceBands();
        if (sourceBands != null &&
            (sourceBands.length != 1 ||
             sourceBands[0] != 0)) {
            throw new IllegalArgumentException("Cannot sub-band image!");
        }

        // Get source region and subsampling factors
        Rectangle sourceRegion = p.getSourceRegion();
        if (sourceRegion != null) {
            // Clip to actual image bounds
            sourceRegion = sourceRegion.intersection(sourceBounds);
            sourceBounds.setBounds(sourceRegion);
        }

        // Adjust for subsampling offsets
        int gridX = p.getSubsamplingXOffset();
        int gridY = p.getSubsamplingYOffset();
        sourceBounds.x += gridX;
        sourceBounds.y += gridY;
        sourceBounds.width -= gridX;
        sourceBounds.height -= gridY;

        // Get subsampling factors
        periodX = p.getSourceXSubsampling();
        periodY = p.getSourceYSubsampling();
    }

    // Compute output dimensions
    destSize.setSize((sourceBounds.width + periodX - 1)/periodX,
                     (sourceBounds.height + periodY - 1)/periodY);
    if (destSize.width <= 0 || destSize.height <= 0) {
        throw new IllegalArgumentException("Empty source region!");
    }
}