所以我有一个形成路径的点数组(x,y)。我需要计算周围多边形的点。基本上CGPathCreateCopyByStrokingPath
,如果您熟悉 iOS。不幸的是,ObjC 不是一种选择。我需要在 Javascript、PHP 等中实现它。
-------
| | |
| | |
\ \ \
\ \ \
\ \ \
\ \ \
\ \ \-----------
\ \----------- |
\---------------
为糟糕的 ascii 艺术道歉。
我有一个 Javascript 的半工作版本,但我有角落的问题。
function pathToPoly(points) {
var numOfPoints = points.length;
var fullPath = [];
var leftPaths = [];
var rightPaths = [];
var pad = 20;
for(var i=0; i<numOfPoints-1; i++) {
var pointA = points[i];
var pointB = points[i+1];
var slope = (pointB.Y - pointA.Y) / (pointB.X - pointA.X);
var inverseSlope = -1 / slope;
var inverseAngle = Math.atan(inverseSlope);
if(inverseAngle < 0) {
leftPaths.push({
X1: pointA.X - pad * Math.cos(inverseAngle),
Y1: pointA.Y - pad * Math.sin(inverseAngle),
X2: pointB.X - pad * Math.cos(inverseAngle),
Y2: pointB.Y - pad * Math.sin(inverseAngle)
});
rightPaths.push({
X1: pointA.X + pad * Math.cos(inverseAngle),
Y1: pointA.Y + pad * Math.sin(inverseAngle),
X2: pointB.X + pad * Math.cos(inverseAngle),
Y2: pointB.Y + pad * Math.sin(inverseAngle)
});
} else {
rightPaths.push({
X1: pointA.X - pad * Math.cos(inverseAngle),
Y1: pointA.Y - pad * Math.sin(inverseAngle),
X2: pointB.X - pad * Math.cos(inverseAngle),
Y2: pointB.Y - pad * Math.sin(inverseAngle)
});
leftPaths.push({
X1: pointA.X + pad * Math.cos(inverseAngle),
Y1: pointA.Y + pad * Math.sin(inverseAngle),
X2: pointB.X + pad * Math.cos(inverseAngle),
Y2: pointB.Y + pad * Math.sin(inverseAngle)
});
}
if(drawSides) {
var leftSide = leftPaths[i];
var rightSide = rightPaths[i];
context.beginPath();
context.moveTo(leftSide.X1, leftSide.Y1);
context.lineTo(leftSide.X2, leftSide.Y2);
context.lineWidth = 1;
context.strokeStyle = 'yellow';
context.stroke();
context.beginPath();
context.moveTo(rightSide.X1, rightSide.Y1);
context.lineTo(rightSide.X2, rightSide.Y2);
context.lineWidth = 1;
context.strokeStyle = 'cyan';
context.stroke();
}
}
for(var i=0; i<numOfPoints-1; i++) {
var line1 = leftPaths[i];
var line2 = leftPaths[i+1];
fullPath.push({
X: line1.X1,
Y: line1.Y1
});
fullPath.push({
X: line1.X2,
Y: line1.Y2,
});
if(line2) {
fullPath.push({
X: line2.X1,
Y: line2.Y1,
});
}
}
fullPath.push({
X: leftPaths[numOfPoints-2].X2,
Y: leftPaths[numOfPoints-2].Y2
});
for(var i=numOfPoints-2; i>=0; i--) {
var line1 = rightPaths[i];
var line2 = rightPaths[i-1];
fullPath.push({
X: line1.X2,
Y: line1.Y2
});
fullPath.push({
X: line1.X1,
Y: line1.Y1,
});
if(line2) {
fullPath.push({
X: line2.X2,
Y: line2.Y2,
});
}
}
fullPath.push({
X: rightPaths[0].X1,
Y: rightPaths[0].Y1
});
return fullPath;
}
此代码在每个段的每一侧绘制平行线,并将它们连接起来。但是对于轮流,我的方法会创建一个无效的多边形。两侧“交换”并生成“反向”区域。并且能够计算面积对我的应用程序至关重要。
示例(我的声誉太低,无法发布图片):蓝色效果很好,但红色失败(注意右下角如何转,两边交换)。
![example](http://www.originalfunction.com/stackoverflow_16590082-1.png)
有什么建议么?