java 多边形_java-向多边形添加点

这篇博客介绍了一个使用Java扩展Polygon类的方法,通过创建一个名为MyPoly的类,实现了在多边形中插入点的功能。代码示例展示了如何在正方形中插入一个点,生成一个新的五边形。主要涉及了PathIterator接口和Segment类型。
摘要由CSDN通过智能技术生成

扩展@normalocity的想法,这似乎是一种可能的方法.

附录:仅供参考,此方法仅使用公共API,但其他变体也是可能的.

安慰:

MoveTo: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

LineTo: [0.0, 10.0, 0.0, 0.0, 0.0, 0.0]

LineTo: [10.0, 10.0, 0.0, 0.0, 0.0, 0.0]

LineTo: [10.0, 0.0, 0.0, 0.0, 0.0, 0.0]

Close: [10.0, 0.0, 0.0, 0.0, 0.0, 0.0]

MoveTo: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

LineTo: [1.0, 5.0, 0.0, 0.0, 0.0, 0.0]

LineTo: [0.0, 10.0, 0.0, 0.0, 0.0, 0.0]

LineTo: [10.0, 10.0, 0.0, 0.0, 0.0, 0.0]

LineTo: [10.0, 0.0, 0.0, 0.0, 0.0, 0.0]

Close: [10.0, 0.0, 0.0, 0.0, 0.0, 0.0]

码:

import java.awt.Point;

import java.awt.Polygon;

import java.awt.geom.PathIterator;

import java.util.Arrays;

/** @see https://stackoverflow.com/questions/5877646 */

public class MyPoly extends Polygon {

public static void main(String[] args) {

final MyPoly square = new MyPoly();

square.addPoint(0, 0);

square.addPoint(0, 10);

square.addPoint(10, 10);

square.addPoint(10, 0);

System.out.println(square.toString());

MyPoly pentagon = square.insert(1, new Point(1, 5));

System.out.println(pentagon.toString());

}

/**

* Insert a point at the specified index

*

* @param index at which to insert the new point

* @param point the Point to insert

* @return a new Polygon with the new Point

*/

public MyPoly insert(int index, Point point) {

MyPoly mp = new MyPoly();

PathIterator pi = this.getPathIterator(null);

double[] coords = new double[6];

int i = 0;

while (!pi.isDone()) {

if (i == index) {

mp.addPoint(point.x, point.y);

} else {

if (pi.currentSegment(coords) != PathIterator.SEG_CLOSE) {

mp.addPoint((int) coords[0], (int) coords[1]);

}

pi.next();

}

i++;

}

return mp;

}

@Override

public String toString() {

PathIterator pi = this.getPathIterator(null);

double[] coords = new double[6];

StringBuilder sb = new StringBuilder();

while (!pi.isDone()) {

int kind = pi.currentSegment(coords);

switch (kind) {

case PathIterator.SEG_MOVETO:

sb.append("MoveTo: ");

break;

case PathIterator.SEG_LINETO:

sb.append("LineTo: ");

break;

case PathIterator.SEG_CLOSE:

sb.append("Close: ");

break;

default:

throw new IllegalArgumentException("Bad path segment");

}

sb.append(Arrays.toString(coords));

sb.append("

");

pi.next();

}

return sb.toString();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值