Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / ViewPort.java @ 9515

History | View | Annotate | Download (23.2 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.fmap;
42

    
43
import java.awt.Color;
44
import java.awt.Dimension;
45
import java.awt.Point;
46
import java.awt.geom.AffineTransform;
47
import java.awt.geom.NoninvertibleTransformException;
48
import java.awt.geom.Point2D;
49
import java.awt.geom.Rectangle2D;
50
import java.util.ArrayList;
51

    
52
import org.cresques.cts.GeoCalc;
53
import org.cresques.cts.IProjection;
54
import org.cresques.cts.gt2.CSUTM;
55

    
56
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
57
import com.iver.utiles.StringUtilities;
58
import com.iver.utiles.XMLEntity;
59

    
60

    
61
/**
62
 * Clase con atributos de la vista.
63
 * 050211, jmorell: A?ado los Grados como unidad de mapa.
64
 *
65
 * @author Vicente Caballero Navarro
66
 */
67
public class ViewPort {
68
        public static int KILOMETROS = 0;
69
        public static int METROS = 1;
70
        public static int CENTIMETRO = 2;
71
        public static int MILIMETRO = 3;
72
        public static int MILLAS = 4;
73
        public static int YARDAS = 5;
74
        public static int PIES = 6;
75
        public static int PULGADAS = 7;
76
        public static int GRADOS = 8;
77

    
78
        /**
79
         * Resoluci?n (Puntos por pulgada) de la vista actual. Se necesita para los
80
         * c?lculos de escala geogr?fica.
81
         */
82
        private static int dpi = java.awt.Toolkit.getDefaultToolkit()
83
                                                                                         .getScreenResolution();
84
        private Rectangle2D extent;
85
        private Rectangle2D adjustedExtent;
86
        private ExtentHistory extents = new ExtentHistory();
87
        private Dimension imageSize;
88
        private AffineTransform trans = new AffineTransform();
89
        private int distanceUnits = METROS;
90
        private int mapUnits = METROS;
91
        private ArrayList listeners = new ArrayList();
92
        private Point2D offset = new Point2D.Double(0, 0);
93
        private Rectangle2D clip;
94
        private Color backColor = null; //Color.WHITE;
95
        private IProjection proj;
96
        private double dist1pixel;
97
        private double dist3pixel;
98
        private double scale;
99
        private Rectangle2D cliprect;
100
        private boolean adjustableExtent=true;
101

    
102
        /**
103
         * Crea un nuevo ViewPort.
104
         *
105
         * @param proj Proyecci?n.
106
         */
107
        public ViewPort(IProjection proj) {
108
                // Por defecto
109
                this.proj = proj;
110
        }
111

    
112
        /**
113
         * Sets the adjustable option, so the extent is automatically adjusted to view aspect.
114
         *
115
         * @param boolean Adjustable.
116
         */
117
        public void setAdjustable(boolean adjustable) {
118
                adjustableExtent = adjustable;
119
        }
120

    
121
        /**
122
         * A?ade un ViewPortListener al extentListener.
123
         *
124
         * @param arg0 ViewPortListener.
125
         *
126
         * @return True si ha sido a?adida correctamente.
127
         */
128
        public boolean addViewPortListener(ViewPortListener arg0) {
129
                if (!listeners.contains(arg0))
130
                        return listeners.add(arg0);
131
                return false;
132
        }
133

    
134

    
135
        /**
136
         * Borra el ViewPortListener que se pasa como par?metro delos
137
         * extentListener.
138
         *
139
         * @param arg0 ViewPortListener.
140
         *
141
         * @return True si ha sido borrado correctamente.
142
         */
143
        public boolean removeViewPortListener(ViewPortListener arg0) {
144
                return listeners.remove(arg0);
145
        }
146

    
147
        /**
148
         * Devuelve la distancia en pixels a partir de una distancia real.
149
         *
150
         * @param d Distancia real.
151
         *
152
         * @return Distancia en pixels.
153
         */
154
        public int fromMapDistance(double d) {
155
                Point2D.Double pWorld = new Point2D.Double(1, 1);
156
                Point2D.Double pScreen = new Point2D.Double();
157

    
158
                try {
159
                        trans.deltaTransform(pWorld, pScreen);
160
                } catch (Exception e) {
161
                        System.err.print(e.getMessage());
162
                }
163

    
164
                return (int) (d * pScreen.x);
165
        }
166

    
167
        /**
168
         * Devuelve un punto en pixels a partir de una coordenada X e Y real.
169
         *
170
         * @param x Coordenada X real.
171
         * @param y Coordenada Y real.
172
         *
173
         * @return Punto en pixels.
174
         */
175
        public Point2D fromMapPoint(double x, double y) {
176
                Point2D.Double pWorld = new Point2D.Double(x, y);
177
                Point2D.Double pScreen = new Point2D.Double();
178

    
179
                try {
180
                        trans.transform(pWorld, pScreen);
181
                } catch (Exception e) {
182
                        System.err.print(e.getMessage());
183
                }
184

    
185
                return pScreen;
186
        }
187

    
188
        /**
189
         * Devuelve el punto en pixels a partir de un punto real.
190
         *
191
         * @param point Punto real.
192
         *
193
         * @return Punto en pixels.
194
         */
195
        public Point2D fromMapPoint(Point2D point) {
196
                return fromMapPoint(point.getX(), point.getY());
197
        }
198

    
199
        /**
200
         * Devuelve un punto real a partir de una coordenada X e Y en pixels.
201
         *
202
         * @param x Coordenada X en pixels.
203
         * @param y Coordenada Y en pixels.
204
         *
205
         * @return Punto real.
206
         */
207
        public Point2D toMapPoint(int x, int y) {
208
                Point pScreen = new Point(x, y);
209

    
210
                return toMapPoint(pScreen);
211
        }
212

    
213
        public Rectangle2D toMapRectangle(Rectangle2D r){
214
                Rectangle2D rect=new Rectangle2D.Double();
215
                Point2D p1=toMapPoint((int)r.getX(),(int)r.getY());
216
                Point2D p2=toMapPoint((int)r.getMaxX(),(int)r.getMaxY());
217
                rect.setFrameFromDiagonal(p1,p2);
218
                return rect;
219
        }
220
        /**
221
         * Devuelve la distancia real a partir de la distancia en pixels.
222
         *
223
         * @param d Distancia en pixels.
224
         *
225
         * @return Distancia real.
226
         */
227
        public double toMapDistance(int d) {
228
                double dist = d / trans.getScaleX();
229

    
230
                return dist;
231
        }
232

    
233
        /**
234
         * Devuelve un punto real a partir de un punto en pixels.
235
         *
236
         * @param pScreen Punto en pixels.
237
         *
238
         * @return Punto real.
239
         *
240
         * @throws RuntimeException
241
         */
242
        public Point2D toMapPoint(Point2D pScreen) {
243
                Point2D.Double pWorld = new Point2D.Double();
244
                AffineTransform at;
245

    
246
                try {
247
                        at = trans.createInverse();
248
                        at.transform(pScreen, pWorld);
249
                } catch (NoninvertibleTransformException e) {
250
                        throw new RuntimeException(e);
251
                }
252

    
253
                return pWorld;
254
        }
255

    
256
        /**
257
         * Calcula la distancia entre dos puntos en unidades de usuario. Los puntos
258
         * est?n en unidades de usuario. Se tiene en cuenta la proyecci?n, con lo
259
         * que es INDISPENSABLE que la variable proj contenga el valor correcto de
260
         * la proyecci?n.
261
         *
262
         * @param pt1
263
         * @param pt2
264
         *
265
         * @return distancia real.
266
         */
267
        public double distanceWorld(Point2D pt1, Point2D pt2) {
268
                double dist = -1;
269
                dist = pt1.distance(pt2);
270

    
271
                if ((proj != null) && !(proj instanceof CSUTM)) {
272
                        dist = new GeoCalc(proj).distanceVincenty(proj.toGeo(pt1),
273
                                        proj.toGeo(pt2));
274
                }
275

    
276
                return dist*MapContext.CHANGEM[getMapUnits()];
277
        }
278

    
279
        /**
280
         * Rellena el extent anterior como actual.
281
         */
282
        public void setPreviousExtent() {
283
                extent = extents.removePrev();
284

    
285
                //Calcula la transformaci?n af?n
286
                calculateAffineTransform();
287

    
288
                // Lanzamos los eventos de extent cambiado
289
                callExtentChanged(getAdjustedExtent());
290
        }
291

    
292
        /**
293
         * <p>
294
         * When the zoom changes (for instance when using the zoom in or zoom out tools,
295
         * but also zooming to a selected feature or shape) the extent that covers that
296
         * area is the value returned by this method. It is not the actual area shown
297
         * in the view because it does not care about the aspect ratio. However, any
298
         * part of the real world contained in this extent is shown in the view.<br>
299
         * </p>
300
         * <p>
301
         * Probably <b>this is not what you are looking for</b>. If you are looking for
302
         * the complete extent currently shown, you must use getAdjustedExtent() method
303
         * which returns the extent that contains this one but regarding the current
304
         * view's aspect ratio.
305
         * </p>
306
         * @return Extent.
307
         */
308
        public Rectangle2D getExtent() {
309
                return extent;
310
        }
311

    
312
        /**
313
         * Inserta el extent.
314
         *
315
         * @param r Extent.
316
         */
317
        public void setExtent(Rectangle2D r) {
318
                if (extent != null) {
319
                        extents.put(extent);
320
                }
321

    
322
                //Esto comprueba que el extent no es de anchura o altura = "0"
323
                //y si es as? lo redimensiona.
324
                if (r!=null &&((r.getWidth() == 0) || (r.getHeight() == 0))) {
325
                        extent = new Rectangle2D.Double(r.getMinX() - 0.1,
326
                                        r.getMinY() - 0.1, r.getWidth() + 0.2, r.getHeight() + 0.2);
327
                } else {
328
                        extent = r;
329
                }
330

    
331
                //Calcula la transformaci?n af?n
332
                calculateAffineTransform();
333

    
334
                // Lanzamos los eventos de extent cambiado
335
                callExtentChanged(getAdjustedExtent());
336
        }
337

    
338
        /**
339
         * Refresca el extent.
340
     *
341
         */
342
        public void refreshExtent() {
343
                //this.scale = scale;
344

    
345
                //Calcula la transformaci?n af?n
346
                calculateAffineTransform();
347

    
348
                // Lanzamos los eventos de extent cambiado
349
                callExtentChanged(getAdjustedExtent());
350
        }
351

    
352
        /**
353
         * Devuelve la escala. Debe estar siempre actualizada y no calcularse nunca
354
         * aqu? pues se utiliza en el dibujado para cada geometr?a
355
         *
356
         * @return Escala.
357
         */
358
        public double getScale() {
359
                return proj.getScale(extent.getMinX(), extent.getMaxX(),
360
                        imageSize.getWidth(), dpi);
361
        }
362

    
363
        /**
364
         * Devuelve la matriz de transformaci?n.
365
         *
366
         * @return Matriz de transformaci?n.
367
         */
368
        public AffineTransform getAffineTransform() {
369
                return trans;
370
        }
371

    
372
        /**
373
         * Devuelve las dimensiones de la imagen.
374
         *
375
         * @return Returns the imageSize.
376
         */
377
        public Dimension getImageSize() {
378
                return imageSize;
379
        }
380

    
381
        /**
382
         * Inserta las dimensiones de la imagen.
383
         *
384
         * @param imageSize The imageSize to set.
385
         */
386
        public void setImageSize(Dimension imageSize) {
387
                this.imageSize = imageSize;
388
                calculateAffineTransform();
389
        }
390

    
391
        /**
392
         * Llamada a los listeners tras el cambio de extent.
393
         *
394
         * @param newRect Extent.
395
         */
396
        private void callExtentChanged(Rectangle2D newRect) {
397
                ExtentEvent ev = ExtentEvent.createExtentEvent(newRect);
398

    
399
                for (int i = 0; i < listeners.size(); i++) {
400
                        ViewPortListener listener = (ViewPortListener) listeners.get(i);
401
                        listener.extentChanged(ev);
402
                }
403
        }
404

    
405
        /**
406
         * Llamada a los listeners tras el cambio de color.
407
         *
408
         * @param c Color.
409
         */
410
        private void callColorChanged(Color c) {
411
                ColorEvent ce = ColorEvent.createColorEvent(c);
412

    
413
                for (int i = 0; i < listeners.size(); i++) {
414
                        ViewPortListener listener = (ViewPortListener) listeners.get(i);
415
                        listener.backColorChanged(ce);
416
                }
417
        }
418
        /**
419
         * Llamada a los listeners tras el cambio de extent.
420
         *
421
         * @param newRect Extent.
422
         */
423
        private void callProjectionChanged(IProjection projection) {
424
                ProjectionEvent ev = ProjectionEvent.createProjectionEvent(projection);
425

    
426
                for (int i = 0; i < listeners.size(); i++) {
427
                        ViewPortListener listener = (ViewPortListener) listeners.get(i);
428
                        listener.projectionChanged(ev);
429
                }
430
        }
431

    
432

    
433
        /**
434
         * C?lculo de la matriz de transformaci?n.
435
         *
436
         * @throws RuntimeException
437
         */
438
        private void calculateAffineTransform() {
439
                if ((imageSize == null) || (extent == null) ||
440
                                (imageSize.getWidth() <= 0) || (imageSize.getHeight() <= 0)) {
441
                        return;
442
                }
443

    
444
                AffineTransform escalado = new AffineTransform();
445
                AffineTransform translacion = new AffineTransform();
446

    
447
                double escalaX;
448
                double escalaY;
449

    
450
                escalaX = imageSize.getWidth() / extent.getWidth();
451
                escalaY = imageSize.getHeight() / extent.getHeight();
452

    
453
                double xCenter = extent.getCenterX();
454
                double yCenter = extent.getCenterY();
455
                double newHeight;
456
                double newWidth;
457

    
458
                adjustedExtent = new Rectangle2D.Double();
459

    
460
                if (adjustableExtent) {
461
                        if (escalaX < escalaY) {
462
                                scale = escalaX;
463
                                newHeight = imageSize.getHeight() / scale;
464
                                adjustedExtent.setRect(xCenter - (extent.getWidth() / 2.0),
465
                                        yCenter - (newHeight / 2.0), extent.getWidth(), newHeight);
466
                        } else {
467
                                scale = escalaY;
468
                                newWidth = imageSize.getWidth() / scale;
469
                                adjustedExtent.setRect(xCenter - (newWidth / 2.0),
470
                                        yCenter - (extent.getHeight() / 2.0), newWidth,
471
                                        extent.getHeight());
472
                        }
473
                        escalado.setToScale(scale, -scale);
474
                }
475
                else { // adjusted is same as extent
476
                        scale = escalaX;
477
                        adjustedExtent.setFrame(extent);
478
                        escalado.setToScale(escalaX, -escalaY);
479
                }
480

    
481
                translacion.setToTranslation(-getAdjustedExtent().getX(),
482
                        -getAdjustedExtent().getY() - getAdjustedExtent().getHeight());
483

    
484
                AffineTransform offsetTrans = new AffineTransform();
485
                offsetTrans.setToTranslation(offset.getX(), offset.getY());
486

    
487
                trans.setToIdentity();
488
                trans.concatenate(offsetTrans);
489
                trans.concatenate(escalado);
490

    
491
                trans.concatenate(translacion);
492

    
493
                // Calculamos las distancias de 1 pixel y 3 pixel con esa transformaci?n
494
                // de coordenadas, de forma que est?n precalculadas para cuando las necesitemos
495
                AffineTransform at;
496

    
497
                try {
498
                        at = trans.createInverse();
499

    
500
                        java.awt.Point pPixel = new java.awt.Point(1, 1);
501
                        Point2D.Float pProv = new Point2D.Float();
502
                        at.deltaTransform(pPixel, pProv);
503

    
504
                        dist1pixel = pProv.x;
505
                        dist3pixel = 3 * pProv.x;
506
                } catch (NoninvertibleTransformException e) {
507
                        System.err.println("transformada afin = " + trans.toString());
508
                        System.err.println("extent = " + extent.toString() +
509
                                " imageSize= " + imageSize.toString());
510
                        throw new RuntimeException(e);
511
                }
512
        }
513

    
514
        /**
515
         * Inserta la desviaci?n.
516
         *
517
         * @param p Punto.
518
         */
519
        public void setOffset(Point2D p) {
520
                offset = p;
521
        }
522
        /**
523
         * The offset is the position where to start drawing. The offset of a View is
524
         * always (0, 0) because the drawing area fits with the full window area. But in
525
         * a Layout it is up to the place where the FFrameView is located.
526
         *
527
         * @param p Point, in pixels, where the map starts.
528
         */
529
        public Point2D getOffset() {
530
                return offset;
531
        }
532
        /**
533
         * Inserta el color de fondo.
534
         *
535
         * @param c Color de fondo.
536
         */
537
        public void setBackColor(Color c) {
538
                backColor = c;
539
                callColorChanged(backColor);
540
        }
541

    
542
        /**
543
         * Devuelve el color de fondo.
544
         *
545
         * @return Color de fondo.
546
         */
547
        public Color getBackColor() {
548
                return backColor;
549
        }
550

    
551
        /**
552
         * Returns the extent currently covered by the view.
553
         *
554
         * @return Returns the adjustedExtent.
555
         */
556
        public Rectangle2D getAdjustedExtent() {
557
                if (cliprect!=null){
558
                        return adjustedExtent.createIntersection(cliprect);
559
                }
560
                return adjustedExtent;
561
        }
562

    
563
        /**
564
         * Devuelve la unidad de medida en la que queremos realizar nuestras mediciones y
565
         * en la que se nos mostrar? toda la informaci?n.
566
         *
567
         * @return Returns the distanceUnits.
568
         */
569
        public int getDistanceUnits() {
570
                return distanceUnits;
571
        }
572

    
573
        /**
574
         * Inserta la unidad de medida en la que queremos realizar nuestras mediciones y
575
         * en la que se nos mostrar? toda la informaci?n.
576
         *
577
         * @param distanceUnits The distanceUnits to set.
578
         */
579
        public void setDistanceUnits(int distanceUnits) {
580
                this.distanceUnits = distanceUnits;
581
        }
582

    
583
        /**
584
         * Devuelve la unidad de medida del mapa, es la unidad de medida en la que est? la cartogr?fia que cargamos,
585
         * normalmente en metros.
586
         *
587
         * @return Returns the mapUnits.
588
         */
589
        public int getMapUnits() {
590
                return mapUnits;
591
        }
592

    
593
        /**
594
         * Inserta la unidad de medida del mapa, es la unidad de medida en la que est? la cartogr?fia que cargamos,
595
         * normalmente en metros.
596
         *
597
         * @param mapUnits The mapUnits to set.
598
         */
599
        public void setMapUnits(int mapUnits) {
600
                this.mapUnits = mapUnits;
601
        }
602

    
603
        /**
604
         * Devuelve la anchura de la imagen.
605
         *
606
         * @return anchura en pixels de la imagen.
607
         */
608
        public int getImageWidth() {
609
                return imageSize.width;
610
        }
611

    
612
        /**
613
         * Devuelve la altura de la imagen.
614
         *
615
         * @return altura de la imagen.
616
         */
617
        public int getImageHeight() {
618
                return imageSize.height;
619
        }
620

    
621
        /**
622
         * Devuelve la distancia real de un pixel.
623
         *
624
         * @return Distancia real de un pixel.
625
         */
626
        public double getDist1pixel() {
627
                return dist1pixel;
628
        }
629

    
630
        /**
631
         * Inserta la distancia real de un pixel.
632
         *
633
         * @param dist1pixel Distancia real de un pixel.
634
         */
635
        public void setDist1pixel(double dist1pixel) {
636
                this.dist1pixel = dist1pixel;
637
        }
638

    
639
        /**
640
         * Devuelve la distancia real de tres pixel.
641
         *
642
         * @return Distancia real de tres pixel.
643
         */
644
        public double getDist3pixel() {
645
                return dist3pixel;
646
        }
647

    
648
        /**
649
         * Inserta la distancia real de tres pixels.
650
         *
651
         * @param dist3pixel Distancia real de tres pixels.
652
         */
653
        public void setDist3pixel(double dist3pixel) {
654
                this.dist3pixel = dist3pixel;
655
        }
656

    
657
        /**
658
         * Devuelve los Extents anteriores almacenados.
659
         *
660
         * @return Returns the extents.
661
         */
662
        public ExtentHistory getExtents() {
663
                return extents;
664
        }
665

    
666
        /**
667
         * Devuelve la proyecci?n.
668
         *
669
         * @return Returns the proj.
670
         */
671
        public IProjection getProjection() {
672
                return proj;
673
        }
674

    
675
        /**
676
         * Inserta la proyecci?n.
677
         *
678
         * @param proj The proj to set.
679
         */
680
        public void setProjection(IProjection proj) {
681
                if(this.proj == null || !this.proj.getAbrev().equals(proj.getAbrev())) {
682
                        this.proj = proj;
683
                        callProjectionChanged(proj);
684
                }
685
        }
686

    
687
        /**
688
         * M?todo que solo lo utilizamos a la hora de imprimir. NO lanza
689
         * un calculateAffineTransform, ni recalcula el adjustedExtent.
690
         * TODO: Para evitar este m?todo, habr?a que redefinir el interfaz
691
         * RasterAdapter, y que recibiera un ViewPortData.
692
         * @param at
693
         */
694
        public void setAffineTransform(AffineTransform at)
695
        {
696
            this.trans = at;
697
        }
698

    
699
        /**
700
         * Devuelve el XMLEntity.
701
         *
702
         * @return XMLEntity.
703
         */
704
        public XMLEntity getXMLEntity() {
705
                XMLEntity xml = new XMLEntity();
706
                xml.putProperty("className",this.getClass().getName());
707

    
708
                if (adjustedExtent != null) {
709
                        xml.putProperty("adjustedExtentX", adjustedExtent.getX());
710
                        xml.putProperty("adjustedExtentY", adjustedExtent.getY());
711
                        xml.putProperty("adjustedExtentW", adjustedExtent.getWidth());
712
                        xml.putProperty("adjustedExtentH", adjustedExtent.getHeight());
713
                }
714

    
715
                if (backColor != null)
716
                    xml.putProperty("backColor", StringUtilities.color2String(backColor));
717

    
718
                if (clip != null) {
719
                        xml.putProperty("clipX", clip.getX());
720
                        xml.putProperty("clipY", clip.getY());
721
                        xml.putProperty("clipW", clip.getWidth());
722
                        xml.putProperty("clipH", clip.getHeight());
723
                }
724

    
725
                xml.putProperty("dist1pixel", dist1pixel);
726
                xml.putProperty("dist3pixel", dist3pixel);
727
                xml.putProperty("distanceUnits", distanceUnits);
728

    
729
                if (extent != null) {
730
                        xml.putProperty("extentX", extent.getX());
731
                        xml.putProperty("extentY", extent.getY());
732
                        xml.putProperty("extentW", extent.getWidth());
733
                        xml.putProperty("extentH", extent.getHeight());
734
                }
735

    
736
                xml.addChild(extents.getXMLEntity());
737
                xml.putProperty("mapUnits", mapUnits);
738
                xml.putProperty("offsetX", offset.getX());
739
                xml.putProperty("offsetY", offset.getY());
740

    
741
                if (proj != null) {
742
                        xml.putProperty("proj", proj.getAbrev());
743
                }
744

    
745
                xml.putProperty("scale", scale);
746

    
747
                return xml;
748
        }
749

    
750
        /**
751
         * Crea un nuevo ViewPort a partir del XMLEntity.
752
         *
753
         * @param xml XMLEntity.
754
         *
755
         * @return Nuevo ViewPort.
756
         */
757
        public static ViewPort createFromXML03(XMLEntity xml) {
758
                ViewPort vp = new ViewPort(null);
759

    
760
                if (xml.contains("adjustedExtentX")) {
761
                        vp.adjustedExtent = new Rectangle2D.Double(xml.getDoubleProperty(
762
                                                "adjustedExtentX"),
763
                                        xml.getDoubleProperty("adjustedExtentY"),
764
                                        xml.getDoubleProperty("adjustedExtentW"),
765
                                        xml.getDoubleProperty("adjustedExtentH"));
766
                }
767

    
768
                if (xml.contains("backColor")) {
769
                        vp.setBackColor(StringUtilities.string2Color(xml.getStringProperty(
770
                                                "backColor")));
771
                }
772

    
773
                if (xml.contains("clipX")) {
774
                        vp.clip = new Rectangle2D.Double(xml.getDoubleProperty("clipX"),
775
                                        xml.getDoubleProperty("clipY"),
776
                                        xml.getDoubleProperty("clipW"),
777
                                        xml.getDoubleProperty("clipH"));
778
                }
779

    
780
                vp.setDist1pixel(xml.getDoubleProperty("dist1pixel"));
781
                vp.setDist3pixel(xml.getDoubleProperty("dist3pixel"));
782
                vp.setDistanceUnits(xml.getIntProperty("distanceUnits"));
783
                vp.extents = ExtentHistory.createFromXML03(xml.getChild(0));
784

    
785
                if (xml.contains("extentX")) {
786
                        vp.setExtent(new Rectangle2D.Double(xml.getDoubleProperty("extentX"),
787
                                        xml.getDoubleProperty("extentY"),
788
                                        xml.getDoubleProperty("extentW"),
789
                                        xml.getDoubleProperty("extentH")));
790

    
791
                        //Calcula la transformaci?n af?n
792
                        vp.calculateAffineTransform();
793

    
794
                        // Lanzamos los eventos de extent cambiado
795
                        // vp.callExtentListeners(vp.adjustedExtent);
796
                }
797

    
798
                vp.setMapUnits(xml.getIntProperty("mapUnits"));
799
                vp.setOffset(new Point2D.Double(xml.getDoubleProperty("offsetX"),
800
                                xml.getDoubleProperty("offsetY")));
801

    
802
                if (xml.contains("proj")) {
803
                        vp.proj = CRSFactory.getCRS(xml.getStringProperty("proj"));
804
                }
805

    
806
                //vp.setScale(xml.getDoubleProperty("scale"));
807
                vp.refreshExtent();
808
                return vp;
809
        }
810

    
811
        /**
812
         * Crea un nuevo ViewPort a partir del XMLEntity.
813
         *
814
         * @param xml XMLEntity.
815
         *
816
         * @return Nuevo ViewPort.
817
         */
818
        public static ViewPort createFromXML(XMLEntity xml) {
819
                ViewPort vp = new ViewPort(null);
820

    
821
                if (xml.contains("adjustedExtentX")) {
822
                        vp.adjustedExtent = new Rectangle2D.Double(xml.getDoubleProperty(
823
                                                "adjustedExtentX"),
824
                                        xml.getDoubleProperty("adjustedExtentY"),
825
                                        xml.getDoubleProperty("adjustedExtentW"),
826
                                        xml.getDoubleProperty("adjustedExtentH"));
827
                }
828

    
829
                if (xml.contains("backColor")) {
830
                        vp.setBackColor(StringUtilities.string2Color(xml.getStringProperty(
831
                                                "backColor")));
832
                }else {
833
                        vp.setBackColor(Color.white);
834
                }
835

    
836
                if (xml.contains("clipX")) {
837
                        vp.clip = new Rectangle2D.Double(xml.getDoubleProperty("clipX"),
838
                                        xml.getDoubleProperty("clipY"),
839
                                        xml.getDoubleProperty("clipW"),
840
                                        xml.getDoubleProperty("clipH"));
841
                }
842

    
843
                vp.setDist1pixel(xml.getDoubleProperty("dist1pixel"));
844
                vp.setDist3pixel(xml.getDoubleProperty("dist3pixel"));
845
                vp.setDistanceUnits(xml.getIntProperty("distanceUnits"));
846
                vp.extents = ExtentHistory.createFromXML(xml.getChild(0));
847

    
848
                if (xml.contains("extentX")) {
849
                        vp.setExtent(new Rectangle2D.Double(xml.getDoubleProperty("extentX"),
850
                                        xml.getDoubleProperty("extentY"),
851
                                        xml.getDoubleProperty("extentW"),
852
                                        xml.getDoubleProperty("extentH")));
853

    
854
                        //Calcula la transformaci?n af?n
855
                        vp.calculateAffineTransform();
856

    
857
                        // Lanzamos los eventos de extent cambiado
858
                        // vp.callExtentListeners(vp.adjustedExtent);
859
                }
860

    
861
                vp.setMapUnits(xml.getIntProperty("mapUnits"));
862
                vp.setOffset(new Point2D.Double(xml.getDoubleProperty("offsetX"),
863
                                xml.getDoubleProperty("offsetY")));
864

    
865
                if (xml.contains("proj")) {
866
                        vp.proj = CRSFactory.getCRS(xml.getStringProperty("proj"));
867
                }
868

    
869
                //vp.setScale(xml.getDoubleProperty("scale"));
870
                vp.refreshExtent();
871
                return vp;
872
        }
873

    
874
        /**
875
         * Clona el ViewPort.
876
         *
877
         * @return ViewPort clonado.
878
         */
879
        public ViewPort cloneViewPort() {
880
                return createFromXML(getXMLEntity());
881
        }
882

    
883
        /**
884
         * Devuelve el String con datos del ViewPort.
885
         *
886
         * @return Cadena con datos del ViewPort.
887
         */
888
        public String toString() {
889
                String str;
890
                str = "Datos del viewPort:\nExtent=" + extent + "\nadjustedExtent=" +
891
                        adjustedExtent + "\nimageSize=" + imageSize + "\nescale=" + scale +
892
                        "\ntrans=" + trans;
893

    
894
                return str;
895
        }
896

    
897
        public void setClipRect(Rectangle2D rectView) {
898
                cliprect=rectView;
899

    
900
        }
901

    
902
        public Rectangle2D fromMapRectangle(Rectangle2D r) {
903
                Rectangle2D rect=new Rectangle2D.Double();
904
                Point2D p1=fromMapPoint((int)r.getX(),(int)r.getY());
905
                Point2D p2=fromMapPoint((int)r.getMaxX(),(int)r.getMaxY());
906
                rect.setFrameFromDiagonal(p1,p2);
907
                return rect;
908
        }
909
        public void setScale(long s){
910
                double x=extent.getX();
911
                double y=extent.getY();
912
                double escalaX = imageSize.getWidth() / extent.getWidth();
913
                double w=imageSize.getWidth() / s;
914
                double h=imageSize.getHeight() / s;
915
                double difw = escalaX/s;
916

    
917
                double x1 = (-x * difw) -
918
            x+
919
            extent.getWidth()/2;
920
        double y1 = (-y * difw) -
921
            y +
922
            extent.getHeight()/2;
923
        double w1=extent.getWidth()*difw;
924
        double h1=extent.getHeight()*difw;
925
                extent.setRect(-x1,-y1,w1,h1);
926
        }
927

    
928
}