gpt4 book ai didi

java - java中的放大和缩小?

转载 作者:行者123 更新时间:2023-12-01 10:08:57 24 4
gpt4 key购买 nike

我是java新手,所以如果我的问题有任何歧义,请纠正我的问题。

我的代码放大和缩小正在工作。但我面临的问题是在完成 Zoom_In 时,在缓冲图像上绘制的线条超出了图像。假设在图像边缘绘制一条线,如果稍微改变缩放百分比,该线就会超出图像。比如说 0.2 或 0.3%。

在这里发布我的代码,以便您更好地理解我当前面临的问题。看看吧。

public class PictureBox extends JPanel {

Graphics2D graphics2D;
static BufferedImage image;
private double zoom = 1.0;
private double percentage = .1;
int width = 0,height = 0;

public PictureBox(){
setDoubleBuffered(false);
this.setBorder(UIManager.getBorder("ComboBox.border"));
this.repaint();
}

@Override
public void paintComponent(Graphics g){

super.paintComponent(g);
if(image == null){
image = new BufferedImage(GlobalConstant.imageSize, GlobalConstant.imageSize, BufferedImage.TYPE_INT_RGB);
graphics2D = (Graphics2D)image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
clear();
}
Graphics2D g2D = (Graphics2D) g;

g2D.scale(zoom, zoom);
g2D.drawImage(image, 0, 0, this);
repaint();
}


public final void putPixelForLine(int x1, int y1, int x2, int y2, Color color) {
if(graphics2D != null){
graphics2D.setColor(color);
graphics2D.drawLine(x1, y1, x2, y2);
repaint();
}
}

public void clear() {
graphics2D.setPaint(Color.WHITE);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
repaint();
}

public void originalSize() {
zoom = 1;
}

public void zoomIn() {
zoom += percentage;
if(zoom > 1.66){
zoom = 1.66;
}
if(image != null){
this.setPreferredSize(new Dimension((int)zoom*image.getWidth(),(int)zoom*image.getHeight()));
}

revalidate();
repaint();
}

public void zoomOut() {
zoom -= percentage;
if(zoom < 0.2){
zoom = 0.2;
}
if(image != null){
this.setPreferredSize(new Dimension((int)zoom*image.getWidth(),(int)zoom*image.getHeight()));
}
revalidate();
repaint();
}

}

最佳答案

我希望您遵循以下程序:

你有一个像这样的循环

initiate the image
draw everything you want on the image: call pixelForLine() etc
while(true) {
zoomIn();
repaint();
... wait a bit
}

用于测试放大 - 相当于缩小。

您应该按如下方式更改方法:

a) 在paint()或paintComponent内部调用repaint()是一个明显的缺陷 - 删除那里的重绘。

b) 如果你想看到放大/缩小,改变 jpanel 的大小没有任何意义;如果您更改包含面板和图像的大小,则不会发生任何情况 - 两者都会放大,因此不会发生任何变化。 (您在这里有冲突的要求:似乎您将 jpanel 附加到某处,并且您想要不断更改 jpanel 的大小 - 这不是一个好的做法,但我将其留给您。) - 因此删除 setPreferredSize ... 的东西。如果你想改变某个地方的大小,仍然可以使用 setSize();重绘(); (如果需要的话,也许可以使用 validate() )

public void zoomIn() {
zoom += percentage;
if(zoom > 1.66){
zoom = 1.66;
}
}

c) 从 PixelForLine() 中删除 repaint() - 在图像上绘制线条并重新绘制图像

d) (int)zoomimage.getWidth() 应该是 (int)(zoomimage.getWidth())

关于java - java中的放大和缩小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36280400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com