Java减去行

时间:2014-04-22 04:10:54

标签: java swing user-interface graphics java-2d

所以我在屏幕上绘制了一个简单的矩形,垂直线从它的两侧向下延伸。所以它看起来像这样:
enter image description here

该线实际上是从屏幕顶部一直到底部的1条全线,它看起来有点像切断。但我想做的是将1行分成2行,与矩形相交。所以它看起来像这样:
enter image description here

我在想的是在矩形的左侧(从左上顶点到左下顶点)有一条线,然后从整行中减去该线以得到2条结果线。 / p>

但Java没有行减法功能,所以我有点失落......加上我认为有更好的方法。有什么想法吗?

2 个答案:

答案 0 :(得分:3)

我会使用Java-2D。

enter image description here

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

class RectangleSubtractedFromLines {

    public static BufferedImage getImage() {
        BufferedImage bi = new BufferedImage(600,200,BufferedImage.TYPE_INT_ARGB);

        Graphics2D g = bi.createGraphics();

        Rectangle2D rect = new Rectangle2D.Double(50,50,100,100);
        // we never draw this, it is used as an area slightly bigger than 
        // the actual rectangle, to subract from the lines to give them space.
        int pad = 8;
        Rectangle2D rectBuffer = new Rectangle2D.Double(
                50-pad,50-pad,100+(2*pad),100+(2*pad));

        // we cannot form an Area from a Line2D, however 
        // we CAN form an Area from a (very thin) Rectangle2D
        Rectangle2D line1 = new Rectangle2D.Double(0,50,600,.02d);
        Rectangle2D line2 = new Rectangle2D.Double(0,149.98,600,.02d);

        Area lines = new Area(line1);
        lines.add(new Area(line2));
        lines.subtract(new Area(rectBuffer));

        g.setColor(Color.RED);
        g.setStroke(new BasicStroke(
                3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g.draw(rect);

        g.setColor(Color.MAGENTA.darker().darker());
        g.setStroke(new BasicStroke(
                6, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g.draw(lines);

        g.dispose();

        return bi;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JLabel gui = new JLabel(new ImageIcon(
                        RectangleSubtractedFromLines.getImage()));

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}

答案 1 :(得分:2)

如果这只是一个矩形,你可以使用矩形类的minYmaxY方法(实际上是从RectangularShape类继承的)

 // line 1 (your orange one)
 double x1 = rectangle.getMinX();
 double y1 = 0;
 double x2 = rectangle.getMinX();
 double y2 = rectangle.getMinY();

 // line 2 (your blue one)
 double x1 = rectangle.getMinX();
 double y1 = rectangle.getMaxY();
 double x2 = rectangle.getMinX();
 double y2 = conainer.getHeight(); // height of the container your painting your rectangle in I assume?

如果您正在使用更高级的形状,那么您应该查看@MadProgrammer提到的Area