使用Java2D和Swing为我的Java矢量图形编辑器创建曲线工具

时间:2011-12-14 07:33:24

标签: java swing graphics vector java-2d

我正在创建一个矢量图形编辑器,并成功创建了画笔和一些基本的2D形状,如Rectange,Ellipse,Line等。现在困扰我的是曲线或曲线工具。我通过从 mousePressed 获取原始点然后更新每个 mouseDragged 上的第二个点来创建其他点。这是代码的一部分:

public void mousePressed(MouseEvent e){
    gfx.setColor(Tool.currentColor);
    pos1 = e.getPoint(); //Get the First Point
}
public void mouseReleased(MouseEvent e){
    if(!e.isAltDown() && !e.isMetaDown())

    if(currentShape != null) shapeSet.add(currentShape);
    currentShape = null;
}
public void mouseDragged(MouseEvent e){
    if(e.isAltDown() || e.isMetaDown()) return;
    //the mouse was dragged, so begin painting
    pos2 = e.getPoint();

    int ctool = Tool.currentTool;

    if(ctool == Tool.LINE){
        currentShape = new Line(pos1,pos2,Tool.currentColor,null);
    }else if(ctool == Tool.ELLIPSE){
        currentShape = new Ellipse(pos1,pos2,Tool.currentColor,null);
    }else if(ctool == Tool.RECTANGLE){
        currentShape = new Rectangle(pos1,pos2,Tool.currentColor,null);
    }

    this.repaint();
}

Line,Ellipse等类非常简单,它们只是取点并在重绘中稍后绘制它们。暂时存储在 currentShape 中的所有形状随后将附加到shapeSet,它是抽象类 Shape 的ArrayList。

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);

    gfx.setBackground(Color.WHITE);

    gfx.clearRect(0, 0, img.getWidth(), img.getHeight());
    for(int i=0; i< shapeSet.size(); i++){
        shapeSet.get(i).draw(gfx);
    }
    if(currentShape != null){
        currentShape.draw(gfx);
    }

    g.drawImage(img, 0, 0, null);
} 

img是 BufferedImage ,gfx是img的图形

img = new BufferedImage(640,480,BufferedImage.TYPE_INT_RGB);
gfx = img.createGraphics(); //Graphics2D

现在我将如何创建曲线工具

P.S 如果你想要Shape(Line,Ellipse等)类的代码,只需发表评论,我就会发布。

2 个答案:

答案 0 :(得分:2)

这里有Bézier Curve Editor in Java可能会给你一些想法,但我不确定你是如何将它整合到你的程序中的。

答案 1 :(得分:1)

使用http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/geom/PathIterator.html

您必须定义SEG_QUADTO或SEG_CUBICTO。只需添加一个带有propr双坐标的新段。