gpt4 book ai didi

java - .drawLine() 问题和缓冲图像

转载 作者:行者123 更新时间:2023-12-02 09:44:25 29 4
gpt4 key购买 nike

我有一个绘画程序,并且我已经完成了所有按钮和 slider ,但是我在实际绘画本身方面遇到了问题。当我将光标拖过屏幕而不是一条不间断的线时,我几乎得到了一条我不想要的虚线。以下是 JPanelBufferedImageMouseListener 的代码:

      public void mouseDragged(MouseEvent e) {
Graphics g=buffered.getGraphics();
g.setColor(mycol);
Graphics2D graph=(Graphics2D)g;
BasicStroke stroke=new BasicStroke(30);
graph.setStroke(stroke);
// g.fillRect(xcor, ycor, 20, 20);
/ /varx=e.getX();
ycor=e.getY();
xcor=e.getX();
int bad=xcor;
int good=ycor;
graph.drawLine(xcor, ycor, bad, good);
// buffered.setRGB(xcor, ycor, mycol.getRGB());
repaint();
// g.drawLine(xcor, ycor, x, x)
repaint();


}

最佳答案

  • 只是为了证明我的评论是正确的,我添加了这个答案,尽管有点轻微评论的更改在这里,这是使用mousePressed(...) 而不是 mouseClicked(...)
  • 还有一个补充,因为您想要的 Graphics2D 对象BufferedImage 因此不要使用 getGraphics() 而是始终使用createGraphics() 返回 Graphics2D 对象,因此您真的不必担心 Actor 阵容的问题。

    请看一下下面的示例:

======================

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
import javax.imageio.ImageIO;

public class PaintingExample {

private BufferedImage bImage;
private ImageIcon image;
private JLabel imageLabel;
private int xClicked = 0;
private int yClicked = 0;
private int xDragged = 0;
private int yDragged = 0;

private MouseAdapter mouseListener = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent me) {
xClicked = me.getX();
yClicked = me.getY();
}

@Override
public void mouseDragged(MouseEvent me) {
xDragged = me.getX();
yDragged = me.getY();

Graphics2D g2 = bImage.createGraphics();
g2.setColor(Color.WHITE);
BasicStroke stroke=new BasicStroke(30);
g2.setStroke(stroke);
g2.drawLine(xClicked, yClicked, xDragged, yDragged);
g2.dispose();
imageLabel.setIcon(new ImageIcon(bImage));
}
};

public PaintingExample() {
try {
bImage = ImageIO.read(new URL(
"http://i.imgur.com/fHiBMwI.jpg"));
image = new ImageIcon(bImage);
} catch(Exception e) {
e.printStackTrace();
}
}

private void displayGUI() {
JFrame frame = new JFrame("Painting on Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel contentPane = new JPanel();
imageLabel = new JLabel(image);
imageLabel.addMouseListener(mouseListener);
imageLabel.addMouseMotionListener(mouseListener);

contentPane.add(imageLabel);

frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new PaintingExample().displayGUI();
}
});
}
}

关于java - .drawLine() 问题和缓冲图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11886866/

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