gpt4 book ai didi

Java 在负坐标上绘制图像

转载 作者:行者123 更新时间:2023-12-04 04:52:25 34 4
gpt4 key购买 nike

我想做一些最能用这张图片解释的事情:

image on jpanel

换句话说,我需要将图片的右下部分放到 jpanel 的左上部分,我尝试将 x 和 y 设置为负数,但没有成功,图像根本不显示。有没有简单的方法可以做到这一点?

我正在使用

g.drawImage(img, x, y, null)
//x and y are negative

绘制它。

最佳答案

我会验证你的 x/y 位置计算是否正确,如果你在屏幕上绘画,我会添加一个 ImageObserver 引用到你的 g.drawImage

enter image description here

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class NegativeImage {

public static void main(String[] args) {
new NegativeImage();
}

public NegativeImage() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private BufferedImage img;

public TestPane() {
try {
img = ImageIO.read(new File("/Users/swhitehead/Dropbox/MegaTokyo/Evil_Small.jpg"));
} catch (IOException ex) {
}
}

@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight()- img.getHeight()) / 2;
// Center...
g.drawImage(img, x, y, this);

// Off to the left...
x = -(img.getWidth() / 2);
g.drawImage(img, x, y, this);

// Off to the right...
x = getWidth() - (img.getWidth() / 2);
g.drawImage(img, x, y, this);
}
}
}

关于Java 在负坐标上绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17249256/

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