1

javaShape接口契约和库例程是否允许将多个形状组合成一个对象扩展Shape接口?

例如,我可以定义Flower由几个椭圆组成花瓣和核心的类吗?

还是Shape假设只有一个连续的轮廓?如果是这样,那么Java中是否有任何用于保存多个形状的类,可能是一些用于矢量图形的类?

4

2 回答 2

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;
    }
}
于 2012-06-05T02:24:04.480 回答
1

要像您描述的那样在 Java 中操作形状,您需要使用Area具有这些操作的类。只需将 a 转换ShapeAreawith new Area(Shape)

于 2012-06-04T12:30:49.340 回答