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

SWT/JFace Java Discussion :

Image ne bouge pas malgré le scroll


Sujet :

SWT/JFace Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé Avatar de pingoui
    Homme Profil pro
    Activité professionnelle sans liens avec le developpement
    Inscrit en
    Juillet 2004
    Messages
    584
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Pas de Calais (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Activité professionnelle sans liens avec le developpement
    Secteur : Industrie

    Informations forums :
    Inscription : Juillet 2004
    Messages : 584
    Par défaut Image ne bouge pas malgré le scroll
    Bonjour,

    j'ai un canvas avec un scroll et un simple rectangle dessiner dan le canvas.
    Lorsque je bouge le scroll, il n'y a aucun effet sur le canvas. rien ne bouge !

    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
     
     
    public class WeeklyPlanningCanvas extends Canvas{
     
     
    	private static final float 	MARGIN = 40;// la marge autour du planning
    	private float              	scale = 1f;// l'échelle du planning
     
     
    	public WeeklyPlanningCanvas(Composite parent, int style, WeeklyPlanningController controller) {
    		super(parent, style);
    		this.controller = controller;
     
     
    		Point point = new Point(
    	            Math.round(((float) getPlanningBounds().getWidth() + MARGIN * 2)
    	                       * scale) + 2 * getBorderWidth(),
    	            Math.round(((float) getPlanningBounds().getHeight() + MARGIN * 2)
    	                       * scale) + 2 * getBorderWidth());
    		this.computeSize(point.x, point.y);
    		//ajoute des listeners sur le planning
    		addCanvasListener();
    	}
     
    	public Rectangle2D getPlanningBounds(){
    		return new Rectangle2D.Float(0, 0, 1000, 1000 );
    	}
     
    	/**
             * Ajoute un listener 
             * 
             */
    	private void addCanvasListener() {
    		this.addPaintListener(new PaintListener() {
    			public void paintControl(PaintEvent event) {					
    				WeeklyPlanningCanvas.this.paintControl(event.gc);
    			}
    		});
    	    this.addListener(SWT.Resize, new Listener() {
     
                //@Override
                public void handleEvent(Event event) {
                    // Initialisation de la taille de la scrollbar
                    ScrollBar sbh = WeeklyPlanningCanvas.this.getHorizontalBar();
                    sbh.setMinimum(0);
                    sbh.setMaximum((int) getPlanningBounds().getWidth());
                    sbh.setSelection(0);
                    sbh.setThumb(getSize().x);
     
                    ScrollBar sbv = WeeklyPlanningCanvas.this.getVerticalBar();
                    sbv.setMinimum(0);
                    sbv.setMaximum((int) getPlanningBounds().getHeight());
                    sbv.setSelection(0);
                    sbv.setThumb(getSize().y);                
                }});
     
    	    final ScrollBar hBar = getHorizontalBar ();
    	    hBar.addListener (SWT.Selection, new Listener () {
    	        public void handleEvent (Event e) {
    	            redraw();
    	        }
    	    });
    	    final ScrollBar vBar = getVerticalBar ();
    	    vBar.addListener (SWT.Selection, new Listener () {
    	        public void handleEvent (Event e) {
    	            redraw();
    	        }
    	    });
    	}
     
     
     
    	/**
             * Dessine le canvas
             */
    	private void paintControl(GC gc) {	
            Image image = (Image) getData("double-buffer-image");
            if (image == null || image.getBounds().width != getSize().x || image.getBounds().height != getSize().y) {
              image = new Image(getDisplay(),getSize().x,getSize().y);
              setData("double-buffer-image", image);
            }
            GC imageGC = new GC(image);       
    		paintBackground(imageGC);	    
    		imageGC.setAntialias(SWT.ON);
    		// dessine  un rectangle
    		paintRect(imageGC);
     
    		gc.drawImage(image, 0, 0);
    		imageGC.dispose();
    		gc.dispose();
    	}
     
    	/**
             * Remplit le fond avec la couleur du systeme
             * 
             * @param imageGC
             */
    	private void paintBackground(GC gc) {
    		gc.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
    		gc.fillRectangle(0, 0, this.getSize().x,
    				this.getSize().y);
    	}
     
    	private void paintRect(GC gc){
    		gc.setForeground(this.getDisplay().getSystemColor(
    				SWT.COLOR_GRAY));
    		gc.drawRectangle(300,300,150,150);
    	}
     
     
     
    }
    Un idée ?

    D'avance merci

  2. #2
    Membre Expert
    Avatar de Gueritarish
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2007
    Messages
    1 800
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2007
    Messages : 1 800
    Par défaut
    Salut,

    J'avais trouvé un snippet qui permettait de faire ça... Bon, je retrouve plus l'@, mais j'ai une classe tiré de ce Snippet (un peu modifié pour mes besoins).
    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
    import java.awt.geom.AffineTransform;
    import java.io.File;
    import java.net.MalformedURLException;
     
    import org.eclipse.jface.resource.ImageDescriptor;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.events.ControlAdapter;
    import org.eclipse.swt.events.ControlEvent;
    import org.eclipse.swt.events.PaintEvent;
    import org.eclipse.swt.events.PaintListener;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
    import org.eclipse.swt.graphics.GC;
    import org.eclipse.swt.graphics.Image;
    import org.eclipse.swt.graphics.Rectangle;
    import org.eclipse.swt.widgets.Canvas;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.swt.widgets.ScrollBar;
     
    /**
     * A scrollable image canvas that extends org.eclipse.swt.graphics.Canvas.
     * <p/>
     * It requires Eclipse (version >= 2.1) on Win32/win32; Linux/gtk;
     * MacOSX/carbon.
     * <p/>
     * This implementation using the pure SWT, no UI AWT package is used. For
     * convenience, I put everything into one class. However, the best way to
     * implement this is to use inheritance to create multiple hierarchies.
     * 
     * @author Chengdong Li: cli4@uky.edu
     */
    public class SWTImageCanvas extends Canvas {
     
    	/**
             * The image default height.
             */
    	public static final int IMAGE_HEIGHT = 1000;
     
    	/**
             * The image default width.
             */
    	public static final int IMAGE_WIDTH = 800;
     
    	/* zooming rates in x and y direction are equal. */
    	final float ZOOMIN_RATE = 1.1f; /* zoomin rate */
    	final float ZOOMOUT_RATE = 0.9f; /* zoomout rate */
    	private Image sourceImage; /* original image */
    	private Image screenImage; /* screen image */
    	private AffineTransform transform = new AffineTransform();
     
    	/**
             * @param parent
             * @param pImageLocation
             */
    	public SWTImageCanvas(final Composite parent, final String pImageLocation) {
    		this(parent, SWT.NULL, pImageLocation);
    	}
     
    	/**
             * Constructor for ScrollableCanvas.
             * 
             * @param parent
             *            the parent of this control.
             * @param style
             *            the style of this control.
             */
    	public SWTImageCanvas(final Composite parent, int style,
    			final String pImageLocation) {
    		super(parent, style | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL
    				| SWT.NO_BACKGROUND);
    		addControlListener(new ControlAdapter() { /* resize listener. */
    			public void controlResized(ControlEvent event) {
    				syncScrollBars();
    			}
    		});
    		addPaintListener(new PaintListener() { /* paint listener. */
    			public void paintControl(final PaintEvent event) {
    				paint(event.gc);
    			}
    		});
    		getImageFromLocation(pImageLocation);
    		initScrollBars();
    	}
     
    	/**
             * {@inheritDoc}
             */
    	public void dispose() {
    		if (screenImage != null && !screenImage.isDisposed()) {
    			screenImage.dispose();
    		}
    	}
     
    	/* Paint function */
    	private void paint(GC gc) {
    		Rectangle clientRect = getClientArea(); /* Canvas' painting area */
    		if (sourceImage != null) {
    			Rectangle imageRect = SWT2Dutil.inverseTransformRect(transform,
    					clientRect);
    			int gap = 2; /* find a better start point to render */
    			imageRect.x -= gap;
    			imageRect.y -= gap;
    			imageRect.width += 2 * gap;
    			imageRect.height += 2 * gap;
     
    			Rectangle imageBound = sourceImage.getBounds();
    			imageRect = imageRect.intersection(imageBound);
    			Rectangle destRect = SWT2Dutil.transformRect(transform, imageRect);
     
    			if (screenImage != null)
    				screenImage.dispose();
    			screenImage = new Image(getDisplay(), clientRect.width,
    					clientRect.height);
    			GC newGC = new GC(screenImage);
    			newGC.setClipping(clientRect);
    			newGC.drawImage(sourceImage, imageRect.x, imageRect.y,
    					imageRect.width, imageRect.height, destRect.x, destRect.y,
    					destRect.width, destRect.height);
    			newGC.dispose();
     
    			gc.drawImage(screenImage, 0, 0);
    		} else {
    			gc.setClipping(clientRect);
    			gc.fillRectangle(clientRect);
    			initScrollBars();
    		}
    	}
     
    	/* Initalize the scrollbar and register listeners. */
    	private void initScrollBars() {
    		ScrollBar horizontal = getHorizontalBar();
    		horizontal.setEnabled(false);
    		horizontal.addSelectionListener(new SelectionAdapter() {
    			public void widgetSelected(SelectionEvent event) {
    				scrollHorizontally((ScrollBar) event.widget);
    			}
    		});
    		ScrollBar vertical = getVerticalBar();
    		vertical.setEnabled(false);
    		vertical.addSelectionListener(new SelectionAdapter() {
    			public void widgetSelected(SelectionEvent event) {
    				scrollVertically((ScrollBar) event.widget);
    			}
    		});
    	}
     
    	/* Scroll horizontally */
    	private void scrollHorizontally(ScrollBar scrollBar) {
    		if (sourceImage == null)
    			return;
     
    		AffineTransform af = transform;
    		double tx = af.getTranslateX();
    		double select = -scrollBar.getSelection();
    		af.preConcatenate(AffineTransform.getTranslateInstance(select - tx, 0));
    		transform = af;
    		syncScrollBars();
    	}
     
    	/* Scroll vertically */
    	private void scrollVertically(ScrollBar scrollBar) {
    		if (sourceImage == null)
    			return;
     
    		AffineTransform af = transform;
    		double ty = af.getTranslateY();
    		double select = -scrollBar.getSelection();
    		af.preConcatenate(AffineTransform.getTranslateInstance(0, select - ty));
    		transform = af;
    		syncScrollBars();
    	}
     
    	/**
             * Synchronize the scrollbar with the image. If the transform is out of
             * range, it will correct it. This function considers only following factors
             * :<b> transform, image size, client area</b>.
             */
    	public void syncScrollBars() {
    		if (sourceImage == null) {
    			redraw();
    			return;
    		}
     
    		AffineTransform af = transform;
    		double sx = af.getScaleX(), sy = af.getScaleY();
    		double tx = af.getTranslateX(), ty = af.getTranslateY();
    		if (tx > 0)
    			tx = 0;
    		if (ty > 0)
    			ty = 0;
     
    		ScrollBar horizontal = getHorizontalBar();
    		horizontal.setIncrement((int) (getClientArea().width / 100));
    		horizontal.setPageIncrement(getClientArea().width);
    		Rectangle imageBound = sourceImage.getBounds();
    		int cw = getClientArea().width, ch = getClientArea().height;
    		if (imageBound.width * sx > cw) { /* image is wider than client area */
    			horizontal.setMaximum((int) (imageBound.width * sx));
    			horizontal.setEnabled(true);
    			if (((int) -tx) > horizontal.getMaximum() - cw)
    				tx = -horizontal.getMaximum() + cw;
    		} else { /* image is narrower than client area */
    			horizontal.setEnabled(false);
    			tx = (cw - imageBound.width * sx) / 2; // center if too small.
    		}
    		horizontal.setSelection((int) (-tx));
    		horizontal.setThumb((int) (getClientArea().width));
     
    		ScrollBar vertical = getVerticalBar();
    		vertical.setIncrement((int) (getClientArea().height / 100));
    		vertical.setPageIncrement((int) (getClientArea().height));
    		if (imageBound.height * sy > ch) { /* image is higher than client area */
    			vertical.setMaximum((int) (imageBound.height * sy));
    			vertical.setEnabled(true);
    			if (((int) -ty) > vertical.getMaximum() - ch)
    				ty = -vertical.getMaximum() + ch;
    		} else { /* image is less higher than client area */
    			vertical.setEnabled(false);
    			ty = (ch - imageBound.height * sy) / 2; // center if too small.
    		}
    		vertical.setSelection((int) (-ty));
    		vertical.setThumb((int) (getClientArea().height));
     
    		/* update transform. */
    		af = AffineTransform.getScaleInstance(sx, sy);
    		af.preConcatenate(AffineTransform.getTranslateInstance(tx, ty));
    		transform = af;
     
    		redraw();
    	}
     
    	/**
             * Perform a zooming operation centered on the given point (dx, dy) and
             * using the given scale factor. The given AffineTransform instance is
             * preconcatenated.
             * 
             * @param dx
             *            center x
             * @param dy
             *            center y
             * @param scale
             *            zoom rate
             * @param af
             *            original affinetransform
             */
    	public void centerZoom(double dx, double dy, double scale,
    			AffineTransform af) {
    		af.preConcatenate(AffineTransform.getTranslateInstance(-dx, -dy));
    		af.preConcatenate(AffineTransform.getScaleInstance(scale, scale));
    		af.preConcatenate(AffineTransform.getTranslateInstance(dx, dy));
    		transform = af;
    		syncScrollBars();
    	}
     
    	/**
             * <p>
             * Get the image from the location.
             * </p>
             * 
             * @param pImageLocation
             *            the image location to use.
             */
    	private void getImageFromLocation(final String pImageLocation) {
    		File image = new File(pImageLocation);
    		if (image.exists()) {
    			ImageDescriptor descriptor;
    			try {
    				descriptor = ImageDescriptor.createFromURL(image.toURI()
    						.toURL());
    				if (descriptor != null) {
    					Image createImage = descriptor.createImage();
    					createImage = ImageDescriptor.createFromImageData(
    							createImage.getImageData().scaledTo(IMAGE_WIDTH,
    									IMAGE_HEIGHT)).createImage();
    					sourceImage = createImage;
    				}
    			} catch (MalformedURLException mue) {
    				mue.printStackTrace();
    			}
    		}
    	}
     
    	/**
             * Zoom in around the center of client Area.
             */
    	public void zoomIn() {
    		if (sourceImage == null)
    			return;
    		Rectangle rect = getClientArea();
    		int w = rect.width, h = rect.height;
    		double dx = ((double) w) / 2;
    		double dy = ((double) h) / 2;
    		centerZoom(dx, dy, ZOOMIN_RATE, transform);
    	}
     
    	/**
             * Zoom out around the center of client Area.
             */
    	public void zoomOut() {
    		if (sourceImage == null)
    			return;
    		Rectangle rect = getClientArea();
    		int w = rect.width, h = rect.height;
    		double dx = ((double) w) / 2;
    		double dy = ((double) h) / 2;
    		centerZoom(dx, dy, ZOOMOUT_RATE, transform);
    	}
    }
    Le truc, c'est que tu redessines l'image, mais pas dans la zone qui est couramment affichée...

    Voilà, à+
    Gueritarish

  3. #3
    Membre éclairé Avatar de pingoui
    Homme Profil pro
    Activité professionnelle sans liens avec le developpement
    Inscrit en
    Juillet 2004
    Messages
    584
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Pas de Calais (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Activité professionnelle sans liens avec le developpement
    Secteur : Industrie

    Informations forums :
    Inscription : Juillet 2004
    Messages : 584
    Par défaut
    Merci Gueritarish,

    je vais regarder sérieusement ce bout de code et je te tiens au courant

    pingoui

  4. #4
    Membre éclairé Avatar de pingoui
    Homme Profil pro
    Activité professionnelle sans liens avec le developpement
    Inscrit en
    Juillet 2004
    Messages
    584
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Pas de Calais (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Activité professionnelle sans liens avec le developpement
    Secteur : Industrie

    Informations forums :
    Inscription : Juillet 2004
    Messages : 584
    Par défaut
    Bonjour,

    Merci beaucoup pour ce bout de code qui fonctionne très bien !

    Je l'ai adapté quelque peu pour dessiner un planning avec en abscisse les jours et en ordonnée les ressources humaines.
    Le planning se dessine très bien et le sroll fonctionne à la perfection.
    Je me pose deux petites questions:
    • vu la complexité du code (vision d'un novice) , est ce que je peux refactoriser ce qui concerne l'insertion d'image tout en gardant le fonctionnement du scroll et de zoom (qui me parait très intéressant)
    • j'ai créé une méthode (pour tester) l'insertion d'une tâche dans le planning drawTaskRect(). je fais un redraw directement après l'insertion... je me demande, si c'est très optimisé, surtout quand j'aurai le planning avec une centaine de tâche à redessiner à chaque fois



    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
     
    import java.awt.geom.AffineTransform;
     
    import org.eclipse.swt.SWT;
     
    import org.eclipse.swt.events.ControlAdapter;
    import org.eclipse.swt.events.ControlEvent;
    import org.eclipse.swt.events.PaintEvent;
    import org.eclipse.swt.events.PaintListener;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
     
    import org.eclipse.swt.graphics.Font;
    import org.eclipse.swt.graphics.GC;
    import org.eclipse.swt.graphics.Image;
    import org.eclipse.swt.graphics.Point;
    import org.eclipse.swt.graphics.Rectangle;
    import org.eclipse.swt.widgets.Canvas;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.ScrollBar;
     
    public class WeeklyPlanningCanvas extends Canvas{
     
     
    	private static final float COLUMN_AGENT_WIDTH = 150;
    	private static final float HEADER_HEIGHT = 20;
    	private static final int NUMBER_DAYS_PER_WEEK = 5;
    	private static final int NUMBER_AGENT = 10;
    	private static final int	MAX_WIDTH_BOUNDS = 1500;
    	private static final int	MAX_HEIGHT_BOUNDS = 2000;
     
    	/* zooming rates in x and y direction are equal. */
    	final float ZOOMIN_RATE = 1.1f; /* zoomin rate */
    	final float ZOOMOUT_RATE = 0.9f; /* zoomout rate */
    	private Image sourceImage; /* original image */
    	private Image screenImage; /* screen image */
    	private AffineTransform transform = new AffineTransform();
     
     
    	/**
             * @param parent
             * @param pImageLocation
             */
    	public WeeklyPlanningCanvas(final Composite parent) {
    		this(parent, SWT.NULL);
    	}
     
    	/**
             * Constructor for ScrollableCanvas.
             * 
             * @param parent
             *            the parent of this control.
             * @param style
             *            the style of this control.
             */
    	public WeeklyPlanningCanvas(final Composite parent, int style) {
    		super(parent, style | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL
    				| SWT.NO_BACKGROUND);
    		addControlListener(new ControlAdapter() { /* resize listener. */
    			public void controlResized(ControlEvent event) {
    				syncScrollBars();
    			}
    		});
    		addPaintListener(new PaintListener() { /* paint listener. */
    			public void paintControl(final PaintEvent event) {
    				paint(event.gc);
    			}
    		});
    		paintPlanning();
    		initScrollBars();
    	}
     
    	/**
             * {@inheritDoc}
             */
    	public void dispose() {
    		if (screenImage != null && !screenImage.isDisposed()) {
    			screenImage.dispose();
    		}
    	}
     
    	/* Paint function */
    	private void paint(GC gc) {
    		Rectangle clientRect = getClientArea(); /* Canvas' painting area */
    		if (sourceImage != null) {
     
    			Rectangle imageRect = SWT2Dutil.inverseTransformRect(transform,
    					clientRect);
    			int gap = 2;  //find a better start point to render 
    			imageRect.x -= gap;
    			imageRect.y -= gap;
    			imageRect.width += 2 * gap;
    			imageRect.height += 2 * gap;
     
    			Rectangle imageBound = sourceImage.getBounds();
    			imageRect = imageRect.intersection(imageBound);
    			Rectangle destRect = SWT2Dutil.transformRect(transform, imageRect);
     
    			if (screenImage != null)
    				screenImage.dispose();
    			screenImage = new Image(getDisplay(), clientRect.width,
    					clientRect.height);
    			GC newGC = new GC(screenImage);
    			newGC.setClipping(clientRect);
    			newGC.drawImage(sourceImage, imageRect.x, imageRect.y,
    					imageRect.width, imageRect.height, destRect.x, destRect.y,
    					destRect.width, destRect.height);
    			newGC.dispose();
     
    			gc.drawImage(screenImage, 0, 0);
    		} else {
    			gc.setClipping(clientRect);
    			gc.fillRectangle(clientRect);
    			initScrollBars();
    		}
    	}
     
    	/* Initalize the scrollbar and register listeners. */
    	private void initScrollBars() {
    		ScrollBar horizontal = getHorizontalBar();
    		horizontal.setEnabled(false);
    		horizontal.addSelectionListener(new SelectionAdapter() {
    			public void widgetSelected(SelectionEvent event) {
    				scrollHorizontally((ScrollBar) event.widget);
    			}
    		});
    		ScrollBar vertical = getVerticalBar();
    		vertical.setEnabled(false);
    		vertical.addSelectionListener(new SelectionAdapter() {
    			public void widgetSelected(SelectionEvent event) {
    				scrollVertically((ScrollBar) event.widget);
    			}
    		});
    	}
     
    	/* Scroll horizontally */
    	private void scrollHorizontally(ScrollBar scrollBar) {
    		if (sourceImage == null)
    			return;
     
    		AffineTransform af = transform;
    		double tx = af.getTranslateX();
    		double select = -scrollBar.getSelection();
    		af.preConcatenate(AffineTransform.getTranslateInstance(select - tx, 0));
    		transform = af;
    		syncScrollBars();
    	}
     
    	/* Scroll vertically */
    	private void scrollVertically(ScrollBar scrollBar) {
    		if (sourceImage == null)
    			return;
     
    		AffineTransform af = transform;
    		double ty = af.getTranslateY();
    		double select = -scrollBar.getSelection();
    		af.preConcatenate(AffineTransform.getTranslateInstance(0, select - ty));
    		transform = af;
    		syncScrollBars();
    	}
     
    	/**
             * Synchronize the scrollbar with the image. If the transform is out of
             * range, it will correct it. This function considers only following factors
             * :<b> transform, image size, client area</b>.
             */
    	public void syncScrollBars() {
    		if (sourceImage == null) {
    			redraw();
    			return;
    		}
     
    		AffineTransform af = transform;
    		double sx = af.getScaleX(), sy = af.getScaleY();
    		double tx = af.getTranslateX(), ty = af.getTranslateY();
    		if (tx > 0)
    			tx = 0;
    		if (ty > 0)
    			ty = 0;
     
    		ScrollBar horizontal = getHorizontalBar();
    		horizontal.setIncrement((int) (getClientArea().width / 100));
    		horizontal.setPageIncrement(getClientArea().width);
    		Rectangle imageBound = sourceImage.getBounds();
    		int cw = getClientArea().width, ch = getClientArea().height;
    		if (imageBound.width * sx > cw) { /* image is wider than client area */
    			horizontal.setMaximum((int) (imageBound.width * sx));
    			horizontal.setEnabled(true);
    			if (((int) -tx) > horizontal.getMaximum() - cw)
    				tx = -horizontal.getMaximum() + cw;
    		} else { /* image is narrower than client area */
    			horizontal.setEnabled(false);
    			tx = (cw - imageBound.width * sx) / 2; // center if too small.
    		}
    		horizontal.setSelection((int) (-tx));
    		horizontal.setThumb((int) (getClientArea().width));
     
    		ScrollBar vertical = getVerticalBar();
    		vertical.setIncrement((int) (getClientArea().height / 100));
    		vertical.setPageIncrement((int) (getClientArea().height));
    		if (imageBound.height * sy > ch) { /* image is higher than client area */
    			vertical.setMaximum((int) (imageBound.height * sy));
    			vertical.setEnabled(true);
    			if (((int) -ty) > vertical.getMaximum() - ch)
    				ty = -vertical.getMaximum() + ch;
    		} else { /* image is less higher than client area */
    			vertical.setEnabled(false);
    			ty = (ch - imageBound.height * sy) / 2; // center if too small.
    		}
    		vertical.setSelection((int) (-ty));
    		vertical.setThumb((int) (getClientArea().height));
     
    		/* update transform. */
    		af = AffineTransform.getScaleInstance(sx, sy);
    		af.preConcatenate(AffineTransform.getTranslateInstance(tx, ty));
    		transform = af;
     
    		redraw();
    	}
     
     
    	/**
             * <p>
             * Paint the planning.
             * </p>
             * 
             */
    	private void paintPlanning() {		
    	      Image planImage = new Image(this.getDisplay(), MAX_WIDTH_BOUNDS, MAX_HEIGHT_BOUNDS);
    	      GC gc = new GC(planImage);
    	      paintBackground(gc);	    			
    	      paintHeader(gc);
    	      paintCells(gc);
    	      gc.dispose();
    	      sourceImage = planImage;
    	}
     
    	/**
             * Remplit le fond avec la couleur du systeme
             * 
             * @param imageGC
             */
    	private void paintBackground(GC gc) {
    		gc.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
    		gc.fillRectangle(0, 0, this.getSize().x,
    				this.getSize().y);
    	}
     
    	/**
             * Dessine le header du planning
             * 
             * @param imageGC
             */
    	private void paintHeader(GC gc) {
    		float headerDayWidth = (MAX_WIDTH_BOUNDS - COLUMN_AGENT_WIDTH - 2) / NUMBER_DAYS_PER_WEEK;
    		float xMin = 0;
    		float xMax = xMin + MAX_WIDTH_BOUNDS;
    		float yMin = 0;
    		//Couleur des traits
    		gc.setForeground(this.getDisplay().getSystemColor(
    				SWT.COLOR_GRAY));
    		//Couleur de fond
    		gc.setBackground(this.getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
     
    		//Dessine la case resources
    		gc.fillRectangle((int)xMin, (int)yMin, (int)COLUMN_AGENT_WIDTH, (int)HEADER_HEIGHT);
     
    		//Police d'écriture
    		Font font = new Font(this.getDisplay(), "Arial",14,SWT.BOLD);
    		int i = 1;
    		String text;
     
    		//Dessine les cases jours
    		for(float x = xMin + COLUMN_AGENT_WIDTH; x < xMax;x += headerDayWidth){	
    			//Couleur des traits
    			gc.setForeground(this.getDisplay().getSystemColor(
    					SWT.COLOR_GRAY));
    			gc.drawRectangle((int)x, (int)yMin, (int)headerDayWidth, (int)HEADER_HEIGHT);
    			gc.fillRectangle((int)x+1, (int)yMin+1, (int)headerDayWidth-1, (int)HEADER_HEIGHT-1);
                //Ajoute la police d'écriture
    			gc.setFont(font);
    			//Couleur du texte
    			gc.setForeground(this.getDisplay().getSystemColor(
    					SWT.COLOR_BLACK));
    			text = "Jour "+ i;
    			Point textSize = gc.textExtent(text);
    			int xText = (int) ((x + headerDayWidth / 2) - (textSize.x / 2));
    			int yText = (int) ((yMin + HEADER_HEIGHT / 2) - (textSize.y / 2));
     
    			gc.drawText(text, xText, yText);
    			i++;		
    		}
     
    	}
     
    	/**
             * Dessine les cellules du planning
             * 
             * @param imageGC
             */
    	private void paintCells(GC gc) {
    		float headerDayWidth = (MAX_WIDTH_BOUNDS - COLUMN_AGENT_WIDTH - 2) / NUMBER_DAYS_PER_WEEK;
    		float dayHeight = (MAX_HEIGHT_BOUNDS - HEADER_HEIGHT) / NUMBER_AGENT;
    		float xMin = 0;
    		float xMax = xMin + MAX_WIDTH_BOUNDS;
    		float yMin = HEADER_HEIGHT;
    		float yMax = yMin + MAX_HEIGHT_BOUNDS;
     
    		//Couleur de fond
    		gc.setBackground(this.getDisplay().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
    		//Police d'écriture
    		Font font = new Font(this.getDisplay(), "Arial",12,SWT.BOLD);
     
    		int i = 1;
    		String text;
     
    		for(float y = yMin; y < yMax ;y += dayHeight){
    			//Couleur des traits
    			gc.setForeground(this.getDisplay().getSystemColor(
    					SWT.COLOR_GRAY));
    			//Dessine la case agents
    			gc.drawRectangle((int)xMin, (int)y, (int)COLUMN_AGENT_WIDTH, (int)dayHeight);
    			gc.fillRectangle((int)xMin+1, (int)y+1, (int)COLUMN_AGENT_WIDTH-1, (int)dayHeight-1);
                //Ajoute la police d'écriture
    			gc.setFont(font);
    			//Couleur du texte
    			gc.setForeground(this.getDisplay().getSystemColor(
    					SWT.COLOR_BLACK));
    			text = "Personne "+ i;
    			Point textSize = gc.textExtent(text);
    			int xText = (int) ((xMin + COLUMN_AGENT_WIDTH / 2) - (textSize.x / 2));
    			int yText = (int) ((y + dayHeight / 2) - (textSize.y / 2));
     
    			gc.drawText(text, xText, yText);
    			i++;
    			//Dessine les cases jours
    			for(float x = xMin + COLUMN_AGENT_WIDTH; x < xMax; x += headerDayWidth){
    				//Couleur des traits
    				gc.setForeground(this.getDisplay().getSystemColor(
    						SWT.COLOR_GRAY));
    				gc.drawRectangle((int)x, (int)y, (int)headerDayWidth, (int)dayHeight);
    			}
    		}
    	}
     
     
    	public void drawTaskRect(){		
    	      GC gc = new GC(sourceImage);
    	      gc.drawRectangle(100, 100, 300,300);
    	      gc.dispose();
    	      redraw();
    	}
     
    	/**
             * Perform a zooming operation centered on the given point (dx, dy) and
             * using the given scale factor. The given AffineTransform instance is
             * preconcatenated.
             * 
             * @param dx
             *            center x
             * @param dy
             *            center y
             * @param scale
             *            zoom rate
             * @param af
             *            original affinetransform
             */
    	public void centerZoom(double dx, double dy, double scale,
    			AffineTransform af) {
    		af.preConcatenate(AffineTransform.getTranslateInstance(-dx, -dy));
    		af.preConcatenate(AffineTransform.getScaleInstance(scale, scale));
    		af.preConcatenate(AffineTransform.getTranslateInstance(dx, dy));
    		transform = af;
    		syncScrollBars();
    	}
     
    	/**
             * Zoom in around the center of client Area.
             */
    	public void zoomIn() {
    		if (sourceImage == null)
    			return;
    		Rectangle rect = getClientArea();
    		int w = rect.width, h = rect.height;
    		double dx = ((double) w) / 2;
    		double dy = ((double) h) / 2;
    		centerZoom(dx, dy, ZOOMIN_RATE, transform);
    	}
     
    	/**
             * Zoom out around the center of client Area.
             */
    	public void zoomOut() {
    		if (sourceImage == null)
    			return;
    		Rectangle rect = getClientArea();
    		int w = rect.width, h = rect.height;
    		double dx = ((double) w) / 2;
    		double dy = ((double) h) / 2;
    		centerZoom(dx, dy, ZOOMOUT_RATE, transform);
    	}
     
    }
    Cordialement



    Cordialement

  5. #5
    Membre Expert
    Avatar de Gueritarish
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2007
    Messages
    1 800
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2007
    Messages : 1 800
    Par défaut
    Salut,

    J'ai pas suivi le premier point
    Par contre, pour le second point, utiliser redraw() est "optimisé". Plus que l'utilisation d'update(). En fait, redraw() va marquer une zone comme devant être redessiné tandis qu'update va demander un dessin explicite (immédiatement).
    Avec redraw(), les appels successifs sont "compactés".

    Voilà, à+
    Gueritarish

  6. #6
    Membre éclairé Avatar de pingoui
    Homme Profil pro
    Activité professionnelle sans liens avec le developpement
    Inscrit en
    Juillet 2004
    Messages
    584
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Pas de Calais (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Activité professionnelle sans liens avec le developpement
    Secteur : Industrie

    Informations forums :
    Inscription : Juillet 2004
    Messages : 584
    Par défaut
    Merci beaucoup ! Je garde donc le redraw !

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Image qui rebondi + image au centre qui ne bouge pas
    Par LowTiste dans le forum Général JavaScript
    Réponses: 3
    Dernier message: 25/03/2011, 15h04
  2. [CSS 2.1] Une image qui ne bouge pas par rapport à la résolution de l'écran
    Par beegees dans le forum Mise en page CSS
    Réponses: 0
    Dernier message: 01/02/2010, 13h45
  3. [Image]EZPDF - ezImage pas plus d'une image par PDF ?
    Par Huntress dans le forum Bibliothèques et frameworks
    Réponses: 19
    Dernier message: 29/11/2005, 17h36
  4. Réponses: 6
    Dernier message: 05/05/2005, 23h47
  5. [JLabel][HTML]pourquoi mes images s'affiche pas?!
    Par La Truffe dans le forum Composants
    Réponses: 8
    Dernier message: 29/04/2004, 11h23

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