简体   繁体   English

摆动问题:在pdf图像上绘制矩形,并在放大和缩小时保持其大小和位置一致

[英]Swing issue: drawing rectangles over the pdf image and keep their size and positions consistent when zooming in and out

I have a rather pressing question in regards to Swing, which I haven't touched for many years. 关于Swing,我有一个相当紧迫的问题,我已经好多年没碰到了。

I have a code that allows the user to draw different rectangles on the pdf document (contained within JPanel ). 我有一个代码,允许用户在pdf文档(包含在JPanel )上绘制不同的矩形。 I draw them, move them, resize them, select them, and even write text on them. 我绘制它们,移动它们,调整它们的大小,选择它们,甚至在它们上写文字。 What I can't do is to keep them consistent when I zoom the document. 我无法做的是在缩放文档时保持一致。 As the document gets bigger, the rectangles I've drawn stay at the same position and the same size. 当文档变大时,我绘制的矩形将保持在相同的位置和相同的大小。

I was wondering if there's a relatively easy logic to track the zooming level and, most importantly, update the rectangles accordingly. 我想知道是否有相对简单的逻辑来跟踪缩放级别,最重要的是相应地更新矩形。 I can retrieve zoom factor, it's a float, but, unfortunately, I'm using Rectangle object, which uses int for x , y , height , and width . 我可以检索缩放因子,它是一个浮点数,但是不幸的是,我正在使用Rectangle对象,该对象对xyheightwidth使用int It will be a hassle to convert it to Rectangle.Float , and I wanted to save it for a last resort. 将其转换为Rectangle.Float会很麻烦,我想将其保存以备不时之需。

I've tried to use AffineTransform , but I'm not quite familiar with it, for some reason I'm getting the wrong coordinates for y . 我尝试使用AffineTransform ,但由于某种原因,我对y坐标错误,因此我不太熟悉。 Can anyone explain to me: 谁能向我解释:

  1. What's the best way to control the Rectangle object, as the pdf document gets zoomed in and out? 随着pdf文档的放大和缩小,控制Rectangle对象的最佳方法是什么?
  2. If AffineTransform is the best way, how should I handle it (maybe there's a link to a good explanation, if so - I couldn't find it)? 如果AffineTransform是最好的方法,我应该如何处理(如果有的话,可以提供一个很好的解释的链接-如果找不到,我找不到它)?

This is the only issue I've been struggling with and it's getting a bit frustrating now. 这是我一直在努力的唯一问题,现在变得有些沮丧。

To scale using an AffineTransform : 使用AffineTransform进行缩放:

  1. Get the transform T of the Graphics object G 获取Graphics对象G的变换T
  2. Create an AffineTransform object A 创建一个AffineTransform对象A
  3. Set the scale of A 设置A的小数位数
  4. Set the transform of the G to A G的变换设置为A
  5. Draw the shapes 绘制形状
  6. Set the transform of G back to T G的变换设置回T

Translated into code - assuming scale is the value to scale by: 转换为代码-假设scale是要按以下方式scale的值:

@Override
protected void paintComponent(Graphics gr){
    super.paintComponent(gr);
    Graphics2D g = (Graphics2D)gr;
    AffineTransform prevTransform = g.getTransform();
    AffineTransform at = new AffineTransform(prevTransform);
    at.scale(scale, scale); 
    g.setTransform(at);
    g.drawRect(...);
    g.setTransform(prevTransform); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM