Search code examples
javaswinggraphics2d

How to use Graphics2D g.scale() on only some things but not others?


I want to be able to zoom in my project, and it is working perfectly with a combination of g.scale(x, x) and g.translate(x, y). However, I want something to not scale with everything else (a minimap). Specifically, I am making a minimap that will show the whole screen and the units as 1x1 pixels.

   for(Unit u : units) { //cycle through arraylist of units
        u.drawUnit(g, selectedUnits.contains(u)); //draws the unit, scales perfectly
        g.setColor(Color.blue);
        g.fillOval(rnd((u.getX()/4)/scale), rnd((u.getY()/4)/scale), rnd(1 + 1/scale), rnd(1 + 1/scale));
        //rnd() is just a shorter (int)Math.round()
        //The minimap's dimensions are width/4 x height/4
    }

So i'm wondering if I can do it an easier way because that makes it look really strange at certain scalings.


Solution

  • You can get/set the AffineTransform object associated with the Graphics2D object. This allows you to readily switch back and forth between two or more transforms without having to do the math through the Graphics2D object's scale/translate/rotate methods. For example:

    //render something default transform
    AffineTransform defaultTransform = g.getTransform();
    AffineTransform newTransform = new AffineTransform(defaultTransform);
    newTransform.setScale(xScale, yScale);
    g.setTransform(newTransform);
    //render something with the new transform
    g.setTransform(oldTransform);
    //render something with the original transform