Como você implementar zoom sensível ao cargo dentro de um JScrollPane?
-
02-07-2019 - |
Pergunta
Eu estou tentando implementar zoom sensível ao cargo dentro de um JScrollPane
. O JScrollPane
contém um componente com um paint
personalizado que vai chamar-se dentro de qualquer espaço que é alocado -. Modo zoom é tão fácil quanto usar uma MouseWheelListener
que redimensiona o componente interno conforme necessário
Mas eu também quero zoom em (ou fora de) um ponto para manter esse ponto tão central como possível dentro da vista resultante zoom-in (ou Check-out) (isto é o que eu chamo de zoom 'posição-sensível' ), semelhante à forma como zoom obras em mapas do Google. Estou certo de que este tem sido feito muitas vezes antes - alguém sabe o caminho "certo" para fazê-lo sob Java Swing ?. Seria melhor jogar com as transformações do Graphic2D
em vez de usar JScrollPanes
?
O código de exemplo a seguir:
package test;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class FPanel extends javax.swing.JPanel {
private Dimension preferredSize = new Dimension(400, 400);
private Rectangle2D[] rects = new Rectangle2D[50];
public static void main(String[] args) {
JFrame jf = new JFrame("test");
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(400, 400);
jf.add(new JScrollPane(new FPanel()));
jf.setVisible(true);
}
public FPanel() {
// generate rectangles with pseudo-random coords
for (int i=0; i<rects.length; i++) {
rects[i] = new Rectangle2D.Double(
Math.random()*.8, Math.random()*.8,
Math.random()*.2, Math.random()*.2);
}
// mouse listener to detect scrollwheel events
addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
updatePreferredSize(e.getWheelRotation(), e.getPoint());
}
});
}
private void updatePreferredSize(int n, Point p) {
double d = (double) n * 1.08;
d = (n > 0) ? 1 / d : -d;
int w = (int) (getWidth() * d);
int h = (int) (getHeight() * d);
preferredSize.setSize(w, h);
getParent().doLayout();
// Question: how do I keep 'p' centered in the resulting view?
}
public Dimension getPreferredSize() {
return preferredSize;
}
private Rectangle2D r = new Rectangle2D.Float();
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.red);
int w = getWidth();
int h = getHeight();
for (Rectangle2D rect : rects) {
r.setRect(rect.getX() * w, rect.getY() * h,
rect.getWidth() * w, rect.getHeight() * h);
((Graphics2D)g).draw(r);
}
}
}
Solução
Testado isso, parece funcionar ...
private void updatePreferredSize(int n, Point p) {
double d = (double) n * 1.08;
d = (n > 0) ? 1 / d : -d;
int w = (int) (getWidth() * d);
int h = (int) (getHeight() * d);
preferredSize.setSize(w, h);
int offX = (int)(p.x * d) - p.x;
int offY = (int)(p.y * d) - p.y;
setLocation(getLocation().x-offX,getLocation().y-offY);
getParent().doLayout();
}
Atualizar
Aqui está uma explicação: o p
ponto é a localização do mouse em relação ao FPanel
. Desde que você está dimensionar o tamanho do painel, a localização do p
(em relação ao tamanho do painel) será ampliado pelo mesmo fator. Subtraindo-se a localização atual do local escalado, você recebe o quanto o ponto de 'turnos' quando o painel é redimensionado. Então é simplesmente uma questão de mudar a localização do painel no painel de rolagem pela mesma quantidade na direção oposta para colocar p
de volta sob o cursor do mouse.
Outras dicas
Aqui está uma refatoração menor de solução de @ Kevin K:
private void updatePreferredSize(int wheelRotation, Point stablePoint) {
double scaleFactor = findScaleFactor(wheelRotation);
scaleBy(scaleFactor);
Point offset = findOffset(stablePoint, scaleFactor);
offsetBy(offset);
getParent().doLayout();
}
private double findScaleFactor(int wheelRotation) {
double d = wheelRotation * 1.08;
return (d > 0) ? 1 / d : -d;
}
private void scaleBy(double scaleFactor) {
int w = (int) (getWidth() * scaleFactor);
int h = (int) (getHeight() * scaleFactor);
preferredSize.setSize(w, h);
}
private Point findOffset(Point stablePoint, double scaleFactor) {
int x = (int) (stablePoint.x * scaleFactor) - stablePoint.x;
int y = (int) (stablePoint.y * scaleFactor) - stablePoint.y;
return new Point(x, y);
}
private void offsetBy(Point offset) {
Point location = getLocation();
setLocation(location.x - offset.x, location.y - offset.y);
}
Seu MouseWheelListener também tem de localizar o cursor, mova-o para o centro do JScrollPane e ajustar a xmin / ymin e xmax / ymax do conteúdo a ser exibido.
Eu acho smt como esta deveria estar trabalhando ...
private void updatePreferredSize(int n, Point p) {
double d = (double) n * 1.08;
d = (n > 0) ? 1 / d : -d;
int w = (int) (getWidth() * d);
int h = (int) (getHeight() * d);
preferredSize.setSize(w, h);
// Question: how do I keep 'p' centered in the resulting view?
int parentWdt = this.getParent( ).getWidth( ) ;
int parentHgt = this.getParent( ).getHeight( ) ;
int newLeft = p.getLocation( ).x - ( p.x - ( parentWdt / 2 ) ) ;
int newTop = p.getLocation( ).y - ( p.y - ( parentHgt / 2 ) ) ;
this.setLocation( newLeft, newTop ) ;
getParent().doLayout();
}
EDIT: Mudou algumas coisas.