Zooming in and zooming out within a panel

前端 未结 2 1180
小鲜肉
小鲜肉 2020-12-29 08:56

I have a Panel in which some 2D objects are moving about. I have overridden paintComponent() as necessary. Now I want to be able to zoom in and zoom out that area. When zoom

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-29 09:20

    Easiest way is to modify your panel and introduce a double indicating your zoom level. This double would indicate your scale, where 1 is normal and higher is zoomed in. You can use that double together with Graphics2D in your paintComponent.

    Such as:

    Graphics2D g2 = (Graphics2D) g;
    int w = // real width of canvas
    int h = // real height of canvas
    // Translate used to make sure scale is centered
    g2.translate(w/2, h/2);
    g2.scale(scale, scale);
    g2.translate(-w/2, -h/2);
    

    For the scrolling, put your panel in a JScrollPane and combine that with a getPreferredSize that also uses your zoom scale. JScrollPane uses the preferred size of the component you put in it. It will show scrollbars if the preferred size exceeds its own size.

    If you change the preferred size of your panel so that the width and height it returns is scaled you should be fine. Basically you can just return something like:

    return new Dimension(w * scale, h * scale)
    

提交回复
热议问题