IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

2D Java Discussion :

Problème de transformée affine + zoom


Sujet :

2D Java

Mode arborescent

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Homme Profil pro
    Développeur Java
    Inscrit en
    Février 2015
    Messages
    30
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Vienne (Limousin)

    Informations professionnelles :
    Activité : Développeur Java

    Informations forums :
    Inscription : Février 2015
    Messages : 30
    Par défaut Problème de transformée affine + zoom
    Bonjour amis développeurs.

    Je réalise un composant qui permettra de dessiner des formes prédéfinies dans un panel. On doit également pouvoir déplacer les formes sur une grille et zoomer (in/out).

    Après quelques jours de recherches,de tutos, de tests,..(et de café), je me suis débrouillé comme un grand pour arriver à avoir le comportement que je souhaite pour mon composant. Malheureusement il y a un point que je n'arrive pas a résoudre.

    En background du panel de dessin j'ai une grille, et je souhaite que cette grille grandisse/rétrécisse quand je zoom/dézoom.

    Nom : Grille0.png
Affichages : 318
Taille : 37,9 Ko

    Je récupère donc la transformée affine de mon espace graphique en fonction du zoom et je dessine la grille puis les formes.
    Le comportement de la grille et des formes quand je zoom est conforme à ce à quoi je m'attends, c'est à dire que les points grossissent et l'espace affiché est plus petit :

    Nom : Grille1.png
Affichages : 324
Taille : 38,1 Ko

    Par contre quand je dézoom rien ne se passe comme je l'ai imaginé (d'ou mon message). Dans l'image ci dessous on voit le résultat après plusieurs zoom out à la molette.

    Nom : Grille2.png
Affichages : 298
Taille : 37,5 Ko

    Sur l'image on ne voit pas le curseur de la souris mais il est place en bas a droite de la grille de points. Les coordonnées correspondent à la taille mise à l'échelle du panel.

    Je comprends donc le soucis, j'applique la transformée affine avant le dessin de la grille (sinon elle ne sera pas grossie) mais donc le dessin s'effectue aussi dans les coordonnées transformées.
    J'ai essayé de sauvegarder la transformée affine au début, et de la restaurer juste avant de redessiner la grille
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    ...
     
    final AffineTransform initialTransform = g2.getTransform();
    final AffineTransform tx = getCurrentTransform();
    tx.concatenate(g2.getTransform());
    g2.setTransform(tx);
     
    // Dessin de la grille (après transformation affine pour qu'elle soit à l'échelle)
    g2.setPaint(texture);
    g2.setTransform(initialTransform);
    g2.fillRect(0, 0, scaledPanelWidth, scaledPanelHeight);
    g2.setPaint(null);
    ...
    mais ça n'a pas été concluant.

    Si j'applique la transformée après avoir dessiné la grille elle prend bien toute la taille du panel, mais elle ne change pas en fonction du zoom.
    J'ai également essayé d'inverser la transformée actuelle et de l'appliquer au moment du dessin de la grille uniquement aussi mais sans succès.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
     
    public class GraphView extends JPanel implements MouseListener, MouseMotionListener, MouseWheelListener, KeyListener, GraphModelListener
    {
    	private static final long serialVersionUID = 1L;
     
    	final static float dash[] = { 5.0f };
    	final static BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 10.0f, dash, 0.0f);
     
    	public final int PANEL_WIDTH = 3960;
    	public final int PANEL_HEIGHT = 2048;
     
    	public int scaledPanelWidth = 3960;
    	public int scaledPanelHeight = 2048;
     
    	private final GraphModel graphModel;
    	private final GraphPanel parent;
     
    	private final Rectangle mouseRect;
    	private final Point correctedMousePt;
     
    	private final Point mousePt;
    	private int zoomCenterX;
    	private int zoomCenterY;
     
    	private TexturePaint texture;
    	private final int gap = 5;
    	private double zoom = 1.0d;
    	private final double minScale = 0.3;
    	private final double maxScale = 5.0;
     
    	private boolean debug = false;
    	private boolean waitingNewComponentPosition;
    	private boolean selecting;
     
    	public GraphView(final GraphPanel _parent, final GraphModel _graphModel)
    	{
    		super();
     
    		parent = _parent;
    		graphModel = _graphModel;
     
    		mouseRect = new Rectangle();
    		mousePt = new Point();
    		correctedMousePt = new Point();
     
    		selecting = false;
    		waitingNewComponentPosition = false;
     
    		graphModel.addGraphModelListener(this);
     
    		initGUI();
    		requestFocusInWindow();
    		requestFocus();
    	}
     
    	private void initGUI()
    	{
    		setFocusable(true);
    		setFocusCycleRoot(true);
    		setBackgroundTexture();
    		setOpaque(true);
     
    		addMouseListener(this);
    		addMouseMotionListener(this);
    		addMouseWheelListener(this);
    		addKeyListener(this);
    	}
     
    	@Override
    	public Dimension getPreferredSize()
    	{
    		return new Dimension(scaledPanelWidth, scaledPanelHeight);
    	}
     
    	@Override
    	public void paintComponent(final Graphics g)
    	{
    		final Graphics2D gDebug = (Graphics2D)g.create();
    		final Graphics2D g2 = (Graphics2D)g;
     
    		// On efface le contenu
    		//		g2.clearRect(0, 0, getWidth(), getHeight());
    		g2.clearRect(0, 0, scaledPanelWidth, scaledPanelHeight);
     
    		final AffineTransform initialTransform = g2.getTransform();
     
    		final AffineTransform tx = getCurrentTransform();
    		tx.concatenate(g2.getTransform());
    		g2.setTransform(tx);
     
    		// Dessin de la grille (après transformation affine pour qu'elle soit à l'échelle)
    		g2.setPaint(texture);
    		g2.fillRect(0, 0, scaledPanelWidth, scaledPanelHeight);
    		g2.setPaint(null);
     
     
                    //  Si j'applique la transformée après avoir dessiné la grille celle ci ne se redimensionne pas
    		//		final AffineTransform tx = getCurrentTransform();
    		//		tx.concatenate(g2.getTransform());
    		//		g2.setTransform(tx);
     
    		// Dessin des liens
    		for (final Link link : graphModel.getLinkSet().getLinks())
    		{
    			link.draw(g2);
    		}
     
    		// Dessin des formes
    		for (final GraphicElement shape : graphModel.getNodeSet().getNodes())
    		{
    			shape.draw(g2);
    		}
     
    		if (selecting)
    		{
    			g2.setColor(Color.DARK_GRAY);
    			g2.setStroke(dashed);
    			g2.drawRect(mouseRect.x, mouseRect.y, mouseRect.width, mouseRect.height);
    		}
     
    		if (waitingNewComponentPosition)
    		{
    			g2.setColor(Color.DARK_GRAY);
    			g2.setStroke(dashed);
    			g2.drawRect(correctedMousePt.x - 10, correctedMousePt.y - 10, 20, 20);
    		}
     
    		if (debug)
    		{
    			// On utilise un autre composant de dessin
    			// indépendant de la transformation affine pour afficher des informations en haut à gauche du panel.
    			gDebug.setColor(Color.RED);
    			showDebugInfo(gDebug);
    		}
    		g2.dispose();
    	}
     
    	@Override
    	public void mouseDragged(final MouseEvent e)
    	{
    		if (!waitingNewComponentPosition || debug)
    		{
    			final Point2D correctedOldPoint = getTranslatedPoint(mousePt.x, mousePt.y);
    			final Point2D correctedNewPoint = getTranslatedPoint(e.getX(), e.getY());
     
    			if (selecting)
    			{
    				mouseRect.setBounds((int)Math.min(correctedOldPoint.getX(), correctedNewPoint.getX()), (int)Math.min(correctedOldPoint.getY(), correctedNewPoint.getY()), (int)Math.abs(correctedOldPoint.getX() - correctedNewPoint.getX()), (int)Math.abs(correctedOldPoint.getY() - correctedNewPoint.getY()));
    				GraphicElement.selectRect(graphModel.getNodeSet(), mouseRect);
    			}
    			else
    			{
    				// On calcule la distance entre le clic et le déplacement de la souris
    				final Point delta = new Point();
    				delta.setLocation((correctedNewPoint.getX() - correctedOldPoint.getX()), correctedNewPoint.getY() - correctedOldPoint.getY());
     
    				GraphicElement.updatePosition(graphModel.getNodeSet(), delta);
     
    				mousePt.setLocation(e.getPoint());
    			}
    			repaint();
    		}
    	}
     
    	@Override
    	public void mouseMoved(final MouseEvent e)
    	{
    		final Point2D correctedCoordonates = getTranslatedPoint(e.getPoint().x, e.getPoint().y);
    		correctedMousePt.setLocation(correctedCoordonates.getX(), correctedCoordonates.getY());
    		if (waitingNewComponentPosition || debug)
    		{
    			mousePt.setLocation(e.getPoint());
    			repaint();
    		}
    	}
     
    	@Override
    	public void mouseClicked(final MouseEvent e)
    	{
    		if (waitingNewComponentPosition)
    		{
    			final Point2D correctedCoordonates = getTranslatedPoint(e.getPoint().x, e.getPoint().y);
    			final NewShapeAction action = parent.getCurrentAction();
    			action.setLocation(correctedCoordonates);
    			action.startAction(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null));
     
    			waitingNewComponentPosition = false;
    		}
    	}
     
    	@Override
    	public void mousePressed(final MouseEvent e)
    	{
    		if (!waitingNewComponentPosition)
    		{
    			mousePt.setLocation(e.getPoint());
     
    			final Point2D correctedCoordonates = getTranslatedPoint(mousePt.x, mousePt.y);
    			correctedMousePt.setLocation(correctedCoordonates.getX(), correctedCoordonates.getY());
     
    			// Shift + Clic Gauche
    			if (e.isShiftDown())
    			{
    				GraphicElement.selectToggle(graphModel.getNodeSet(), correctedMousePt);
    			}
    			// Clic droit
    			else if (e.isPopupTrigger())
    			{
    				GraphicElement.selectOne(graphModel.getNodeSet(), correctedMousePt);
    				showPopup(e);
    			}
    			// Clic sur un objet
    			else if (GraphicElement.selectOne(graphModel.getNodeSet(), correctedMousePt))
    			{
    				selecting = false;
    			}
    			else
    			{
    				GraphicElement.selectNone(graphModel.getNodeSet());
    				selecting = true;
    			}
    		}
    		repaint();
    	}
     
    	@Override
    	public void mouseReleased(final MouseEvent e)
    	{
    		selecting = false;
    		mouseRect.setBounds(0, 0, 0, 0);
    		if (e.isPopupTrigger())
    		{
    			showPopup(e);
    		}
     
    		repaint();
    	}
     
    	@Override
    	public void mouseWheelMoved(final MouseWheelEvent e)
    	{
    		if (e.isControlDown())
    		{
    			//			final Point2D correctedCoordonates = getTranslatedPoint(e.getPoint().x, e.getPoint().y);
     
    			mousePt.setLocation(e.getPoint());
    			//						System.out.println("1: ( " + zoomCenterX + "; " + zoomCenterY + " )");
    			//			zoomCenterX = (int)(correctedCoordonates.getX());
    			//			zoomCenterY = (int)(correctedCoordonates.getY());
    			zoomCenterX = 0;
    			zoomCenterY = 0;
     
    			//			System.out.println("2 : ( " + zoomCenterX + "; " + zoomCenterY + " ) \n");
     
    			// Zoom
    			if (e.getWheelRotation() < 0)
    			{
    				zoom += .2 * -e.getWheelRotation();
    				zoom = Math.min(maxScale, zoom);
     
    				scaledPanelWidth = (int)(PANEL_WIDTH * zoom) > 0 ? (int)(PANEL_WIDTH * zoom) : PANEL_WIDTH;
    				scaledPanelHeight = (int)(PANEL_HEIGHT * zoom) > 0 ? (int)(PANEL_HEIGHT * zoom) : PANEL_HEIGHT;
    			}
    			// Dezoom
    			else
    			{
    				zoom += .2 * -e.getWheelRotation();
    				zoom = Math.max(minScale, zoom);
     
    				scaledPanelWidth = (int)(PANEL_WIDTH * zoom) > 0 ? (int)(PANEL_WIDTH * zoom) : PANEL_WIDTH;
    				scaledPanelHeight = (int)(PANEL_HEIGHT * zoom) > 0 ? (int)(PANEL_HEIGHT * zoom) : PANEL_HEIGHT;
    			}
    			setPreferredSize(new Dimension(scaledPanelWidth, scaledPanelHeight));
    			repaint();
    		}
    	}
     
    	@Override
    	public void mouseEntered(final MouseEvent e)
    	{
    	}
     
    	@Override
    	public void mouseExited(final MouseEvent e)
    	{
    	}
     
    	@Override
    	public void graphChanged()
    	{
    		repaint();
    	}
     
    	@Override
    	public void keyTyped(final KeyEvent e)
    	{
    	}
     
    	@Override
    	public void keyPressed(final KeyEvent e)
    	{
    	}
     
    	@Override
    	public void keyReleased(final KeyEvent _e)
    	{
    		// Si on a appuyé sur la touche échap
    		if (_e.getKeyCode() == KeyEvent.VK_ESCAPE)
    		{
    			// Juste après avoir cliqué sur new on annule la création
    			if (waitingNewComponentPosition)
    			{
    				waitingNewComponentPosition = false;
    			}
    			// Ou on annule la sélection
    			else
    			{
    				GraphicElement.selectNone(graphModel.getNodeSet());
    			}
    			repaint();
    		}
     
    		if (_e.getKeyCode() == KeyEvent.VK_ENTER)
    		{
    			zoom = 1.0d;
    			scaledPanelWidth = (int)(PANEL_WIDTH * zoom) > 0 ? (int)(PANEL_WIDTH * zoom) : PANEL_WIDTH;
    			scaledPanelHeight = (int)(PANEL_HEIGHT * zoom) > 0 ? (int)(PANEL_HEIGHT * zoom) : PANEL_HEIGHT;
     
    			repaint();
    		}
    	}
     
    	private void showPopup(final MouseEvent e)
    	{
    		parent.showPopup(e);
    	}
     
    	/**
             * @return the waitingClicPosition
             */
    	public boolean isWaitingNewComponentPosition()
    	{
    		return waitingNewComponentPosition;
    	}
     
    	/**
             * @param waitingClicPosition
             *            the waitingClicPosition to set
             */
    	public void setWaitingNewComponentPosition(final boolean _waitingComponentPosition)
    	{
    		// On met le focus sur la grille
    		requestFocus();
    		waitingNewComponentPosition = _waitingComponentPosition;
    	}
     
    	/**
             * @param debug
             *            the debug to set
             */
    	public void enableDebugInfo(final boolean _debug)
    	{
    		debug = _debug;
    	}
     
    	private void setBackgroundTexture()
    	{
    		// Création de la texture pour le background
    		final BufferedImage bi = new BufferedImage(gap, gap, BufferedImage.TYPE_INT_RGB);
    		final Graphics2D big = bi.createGraphics();
    		big.setColor(Color.white);
    		big.fillRect(0, 0, gap, gap);
    		big.setColor(Color.blue);
    		big.drawLine(0, 0, 0, 0);
    		final Rectangle2D r = new Rectangle(0, 0, gap, gap);
    		texture = new TexturePaint(bi, r);
    		big.dispose();
    	}
     
    	private AffineTransform getCurrentTransform()
    	{
    		final AffineTransform tx = new AffineTransform();
     
    		tx.translate(zoomCenterX, zoomCenterY);
    		tx.scale(zoom, zoom);
    		tx.translate(-zoomCenterX, -zoomCenterY);
     
    		return tx;
    	}
     
    	private void incrementZoom(final double amount)
    	{
    		zoom += amount;
    		zoom = Math.max(minScale, zoom);
    		repaint();
    	}
     
    	/**
             * Convert pixel coordonate to drawing coordonate according to affine transform
             *
             * @param _panelX
             * @param _panelY
             * @return
             */
    	private Point2D getTranslatedPoint(final int _panelX, final int _panelY)
    	{
    		final AffineTransform tx = getCurrentTransform();
    		final Point2D point2d = new Point2D.Double(_panelX, _panelY);
    		try
    		{
    			return tx.inverseTransform(point2d, null);
    		}
    		catch (final NoninvertibleTransformException ex)
    		{
    			ex.printStackTrace();
    			return null;
    		}
    	}
     
    	private void showDebugInfo(final Graphics2D _g2)
    	{
    		_g2.setColor(Color.RED);
    		final int x = 10;
    		int y = 20;
    		_g2.drawString("Panel size: " + scaledPanelWidth + ", " + scaledPanelHeight, x, y);
    		y += 15;
    		_g2.drawString("Mouse Coord in panel: " + correctedMousePt, x, y);
    		y += 15;
    		_g2.drawString("Mouse Coord pixel: " + mousePt, x, y);
    		y += 15;
    		int i = 0;
    		for (final GraphicElement n : graphModel.getNodeSet().getNodes())
    		{
    			if (n.isSelected())
    			{
    				_g2.drawString("Shape" + i + " coord: " + n.getLocation(), x, y + (i * 15));
    				i++;
    			}
    		}
    		_g2.drawString("test", x, y + (i * 15));
    	}
    }
    Je cherche à comprendre comment pouvoir mettre la grille à l'échelle et à la redessiner sur tous l'espace en utilisant le système de coordonnées initial.

    Note : Pour l'instant le zoom se fait sur le point (0,0) normalement il se fait en fonction de la position du curseur de la souris.

    Je joint les sources si besoin.

    Merci d'avoir pris le temps de lire mon pavé . Et a bientôt pour vos idées
    Fichiers attachés Fichiers attachés

Discussions similaires

  1. Problèmes de transformations
    Par javator dans le forum OpenGL
    Réponses: 1
    Dernier message: 11/11/2006, 14h36
  2. [WordML][XSLT] Problème de transformation
    Par fouhaa dans le forum Balisage (X)HTML et validation W3C
    Réponses: 3
    Dernier message: 24/05/2006, 15h22
  3. [XSLT] Problème de transformation XML avec un fichier xslt
    Par seb35 dans le forum Format d'échange (XML, JSON...)
    Réponses: 2
    Dernier message: 24/04/2006, 22h02
  4. [RegEx] Problème pour transformer les url en liens cliquable
    Par AlphaYoDa dans le forum Langage
    Réponses: 2
    Dernier message: 20/02/2006, 13h54
  5. Problème de transformations...
    Par Omfraax dans le forum OpenGL
    Réponses: 7
    Dernier message: 19/01/2006, 18h26

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo