是否java Shape
接口契約和庫例程允許將多個形狀組合成一個對象擴展爲Shape
接口?Java中的形狀組合?
例如,我是否可以定義類Flower
,其中包括花瓣和核心的幾個橢圓?
或Shape
只假設一個連續輪廓?如果是這樣,那麼Java中是否有任何用於保存多個形狀的類,可能是某些向量化圖形的類?
是否java Shape
接口契約和庫例程允許將多個形狀組合成一個對象擴展爲Shape
接口?Java中的形狀組合?
例如,我是否可以定義類Flower
,其中包括花瓣和核心的幾個橢圓?
或Shape
只假設一個連續輪廓?如果是這樣,那麼Java中是否有任何用於保存多個形狀的類,可能是某些向量化圖形的類?
要像使用Java描述的那樣操作Java中的形狀,您需要使用具有這些操作的Area
類。只需將Shape
轉換爲Area
與new Area(Shape)
即可。
這是我的嘗試 - 使用錨定在花朵形狀中心的旋轉變換。
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class DaisyDisplay {
DaisyDisplay() {
BufferedImage daisy = new BufferedImage(
200,200,BufferedImage.TYPE_INT_RGB);
Graphics2D g = daisy.createGraphics();
g.setColor(Color.GREEN.darker());
g.fillRect(0, 0, 200, 200);
Daisy daisyPainter = new Daisy();
daisyPainter.paint(g);
g.dispose();
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(daisy)));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new DaisyDisplay();
}
});
}
}
class Daisy {
public void paint(Graphics2D g) {
Area daisyArea = getDaisyShape();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
paintDaisyPart(g,daisyArea);
g.setTransform(AffineTransform.getRotateInstance(
Math.PI*1/8,
100,100));
paintDaisyPart(g,daisyArea);
g.setTransform(AffineTransform.getRotateInstance(
Math.PI*3/8,
100,100);
paintDaisyPart(g,daisyArea);
g.setTransform(AffineTransform.getRotateInstance(
Math.PI*2/8,
100,100));
paintDaisyPart(g,daisyArea);
}
public void paintDaisyPart(Graphics2D g, Area daisyArea) {
g.setClip(daisyArea);
g.setColor(Color.YELLOW);
g.fillRect(0, 0, 200, 200);
g.setColor(Color.YELLOW.darker());
g.setClip(null);
g.setStroke(new BasicStroke(3));
g.draw(daisyArea);
}
public Area getDaisyShape() {
Ellipse2D.Double core = new Ellipse2D.Double(70,70,60,60);
Area area = new Area(core);
int size = 200;
int pad = 10;
int petalWidth = 50;
int petalLength = 75;
// left petal
area.add(new Area(new Ellipse2D.Double(
pad,(size-petalWidth)/2,petalLength,petalWidth)));
// right petal
area.add(new Area(new Ellipse2D.Double(
(size-petalLength-pad),(size-petalWidth)/2,petalLength,petalWidth)));
// top petal
area.add(new Area(new Ellipse2D.Double(
(size-petalWidth)/2,pad,petalWidth,petalLength)));
// bottom petal
area.add(new Area(new Ellipse2D.Double(
(size-petalWidth)/2,(size-petalLength-pad),petalWidth,petalLength)));
return area;
}
}
你會奇蹟般的失敗嘗試構建一個花的面積爲是因爲這個行:'創建從封閉任何區域(甚至當「關閉」)產生形狀的區域一個空的區域。這個問題的一個常見例子是,由於線不包含任何區域,因此從線生成區域將爲空。 – bezmax
我猜'區域'對象會丟失有關內部線的信息? –
是的。 (我以爲你試圖把它構建成一個橢圓的聯盟,但是,不,這應該可以很好地工作。) –