Search code examples
javaswingscaleshapespoints

My method scale isn't working, what may be the issue?


I have been trying to scale a Shape in java, but I'm having some problems. When i try it the Shape simple dissapears... This method receives 2 points, toScale is the point that i want the shape to extend to, and p1 is the point that I clicked in the rectangle that is around the shape to select (there's a rectangle(boundingBox) surrounding the shape wheter is a polygone or a rectangle or just polylines)

Here's the scale method code:

 public void scale(Point toScale, Point p1) {
        Graphics g = parent.getGraphics();
        int distanceToClicked = 0;
        int distanceToBoundingBox = 0;
        int scaleFactor = 0;
        Vector<Point> pointsAux = new Vector<Point>();          

        Iterator<Point> it = points.iterator();
        while (it.hasNext()){
            Point p = it.next();
            distanceToClicked = (int) Math.sqrt(Math.pow(getCentroid().getX()-p1.getX(), 2)+Math.pow(getCentroid().getY()-p1.getY(),2));
            distanceToBoundingBox = (int) Math.sqrt(Math.pow(getCentroid().getX()-toScale.getX(),2)+Math.pow(getCentroid().getY()-toScale.getY(),2));
            scaleFactor = distanceToClicked/distanceToBoundingBox;
            p = new Point((int)p.getX()*scaleFactor,(int) p.getY()*scaleFactor);
            pointsAux.add(p);
        }
        points.clear();
        points.addAll(pointsAux);
    }

 public Point getCentroid(){
        int sumx = 0;
        int sumy = 0;
        for(int i = 0; i<points.size();i++){
            sumx+=points.get(i).getX();
            sumy+=points.get(i).getY();
        }
         Point centroid = new Point(sumx/points.size(), sumy/points.size());
         return centroid;
    }

Any help would be appreciated Thanks in advance, and eventually I'm sorry for the misunderstanding code


Solution

  • Something like that would do the trick:

    public Collection<Point> scaleShape(float scale, Collection<Point> shape) {
        Point centroid = getCentroid();
        Collection<Point> scaledShape = new ArrayList<>(shape.size());
    
        for (Point point : shape) {
            Point diff = new Point(point.x() - centroid.x(), point.y() - centroid.y());
            Point scaledPoint = new Point(
                (int) (centroid.x() + scale * diff.x()),
                (int) (centroid.y() + scale * diff.y()));
    
            scaledShape.add(scaledPoint);
        }
    
        return scaledShape;
    }
    

    Basically, every points make a linear function with the centroid. Centroid's relative x = 0, while the current computed point is at relative x = 1. You want to find the point if it were at relative x = scale.