在面板内放大和缩小 [英] Zooming in and zooming out within a panel

查看:90
本文介绍了在面板内放大和缩小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个面板,其中一些2D对象在其中移动.我已经根据需要重写了paintComponent().现在,我希望能够放大和缩小该区域.放大时,将出现滚动条,通过滚动条可以滚动查看整个字段.在放大和缩小时,2D对象的大小应相应增加或减小.哪个Swing组件或什至是组件的组合将有助于实现这一目标?

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 zooming in, scrollbars will appear by which one can view the entire field by scrolling. While zooming in and out, the 2D objects should increase or decrease in size accordingly. Which Swing component or rather combination of components will help to achieve this?

推荐答案

最简单的方法是修改面板并引入一个双精度来指示您的缩放级别.此双精度表示您的比例尺,其中1为正常,更高的比例放大.您可以在paintComponent中将其与Graphics2D一起使用.

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.

例如:

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);

对于滚动,将面板放在JScrollPane中,然后将其与也使用缩放比例的getPreferredSize结合起来. JScrollPane使用放置在其中的组件的首选大小.如果首选大小超过其自身大小,它将显示滚动条.

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)

这篇关于在面板内放大和缩小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆