/Users/lyon/j4p/src/gui/layouts/AspectBoundable.java

1    /* 
2     * Created by DocJava, Inc. 
3     * User: lyon 
4     * Date: Mar 20, 2003 
5     * Time: 9:05:23 AM 
6     */ 
7    package gui.layouts; 
8     
9    import java.awt.*; 
10    
11   public class AspectBoundable 
12           implements BoundableInterface { 
13       public void setBounds(Component c, 
14                             int x, int y, 
15                             int w, int h) { 
16           Dimension wantedSize = new Dimension(w, h); 
17           Dimension d = c.getPreferredSize(); 
18           d = scale(d, wantedSize); 
19           c.setBounds(x, y, d.width, d.height); 
20       } 
21    
22       /** 
23        * scale returns a new dimension that has 
24        * the same aspect ratio as the first dimension 
25        * but has no part larger than the second dimension 
26        */ 
27       public Dimension scale(Dimension imageDimension, 
28                              Dimension availableSize) { 
29           double ar = imageDimension.width / (imageDimension.height * 1.0); 
30           double availableAr = availableSize.width / (availableSize.height * 1.0); 
31    
32           int newHeight = (int) (availableSize.width / ar); 
33           int newWidth = (int) (availableSize.height * ar); 
34           if (availableAr < ar) 
35               return new Dimension(availableSize.width, newHeight); 
36           return new Dimension(newWidth, availableSize.height); 
37       } 
38    
39       public Dimension scaleWidth(Dimension d1, Dimension d2) { 
40           double scaleFactor = 
41                   d2.width / (d1.width * 1.0); 
42           return scale(d1, scaleFactor); 
43       } 
44    
45       private Dimension scale(Dimension d1, double scaleFactor) { 
46           return new Dimension((int) (d1.width * scaleFactor), 
47                   (int) (d1.height * scaleFactor)); 
48       } 
49    
50       public Dimension scaleHeight(Dimension d1, Dimension d2) { 
51           double scaleFactor = d2.height / (d1.height * 1.0); 
52           return scale(d1, scaleFactor); 
53       } 
54    
55    
56   } 
57