private void moveVisibleRect(Point center) { JComponent component = scene.getView(); if (component == null) { return; } double zoomFactor = scene.getZoomFactor(); Rectangle bounds = scene.getBounds(); Dimension size = getSize(); double sx = bounds.width > 0 ? (double) size.width / bounds.width : 0.0; double sy = bounds.width > 0 ? (double) size.height / bounds.height : 0.0; double scale = Math.min(sx, sy); int vw = (int) (scale * bounds.width); int vh = (int) (scale * bounds.height); int vx = (size.width - vw) / 2; int vy = (size.height - vh) / 2; int cx = (int) ((double) (center.x - vx) / scale * zoomFactor); int cy = (int) ((double) (center.y - vy) / scale * zoomFactor); Rectangle visibleRect = component.getVisibleRect(); visibleRect.x = cx - visibleRect.width / 2; visibleRect.y = cy - visibleRect.height / 2; component.scrollRectToVisible(visibleRect); this.repaint(); }
public void paint(Graphics g) { Graphics2D gr = (Graphics2D) g; super.paint(g); Rectangle bounds = scene.getBounds(); Dimension size = getSize(); double sx = bounds.width > 0 ? (double) size.width / bounds.width : 0.0; double sy = bounds.width > 0 ? (double) size.height / bounds.height : 0.0; double scale = Math.min(sx, sy); int vw = (int) (scale * bounds.width); int vh = (int) (scale * bounds.height); int vx = (size.width - vw) / 2; int vy = (size.height - vh) / 2; if (image == null || vw != imageWidth || vh != imageHeight) { imageWidth = vw; imageHeight = vh; image = this.createImage(imageWidth, imageHeight); Graphics2D ig = (Graphics2D) image.getGraphics(); ig.scale(scale, scale); scene.setRealZoomFactor(scale); scene.paint(ig); scene.setRealZoomFactor(0.0); } gr.drawImage(image, vx, vy, this); JComponent component = scene.getView(); double zoomFactor = scene.getZoomFactor(); Rectangle viewRectangle = component != null ? component.getVisibleRect() : null; if (viewRectangle != null) { Rectangle window = new Rectangle( (int) ((double) viewRectangle.x * scale / zoomFactor), (int) ((double) viewRectangle.y * scale / zoomFactor), (int) ((double) viewRectangle.width * scale / zoomFactor), (int) ((double) viewRectangle.height * scale / zoomFactor)); window.translate(vx, vy); gr.setColor(new Color(200, 200, 200, 128)); gr.fill(window); gr.setColor(Color.BLACK); gr.drawRect(window.x, window.y, window.width - 1, window.height - 1); } }