java Shape
接口契约和库例程是否允许将多个形状组合到一个扩展Shape
接口的对象中?
例如,我可以定义类Flower
,它将由花瓣和核心的几个椭圆组成?
或者Shape
只假设一个连续的大纲?如果是这样,那么Java中是否存在用于保存多个形状的类,可能是某些用于矢量化图形的类?
答案 0 :(得分:1)
要像您所描述的那样操纵Java中的形状,您需要使用具有这些操作的Area
类。只需使用Shape
将Area
转换为new Area(Shape)
。
答案 1 :(得分:1)
这是我的尝试 - 使用锚定在花形中心的旋转变换。
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;
}
}