# 有一条跟随另一条路的路径[英] Having a path that follows another one

## 推荐答案

```CGContextBeginPath(context);
CGMutablePathRef path = CGPathCreateMutable();

MKMapPoint *mapPoints = itineraryPath.points;
CGPoint previousEdgeNormal = CGPointZero;
CGPoint previousDrawnPoint = CGPointZero;
float offsetDistance = self.pathWidth*2.5;

for(int i = 0; i < itineraryPath.pointCount; i++) {
if(i < itineraryPath.pointCount-1) {
MKMapPoint mapPoint = mapPoints[i];
CGPoint point = [self pointForMapPoint:mapPoint];
MKMapPoint secondMapPoint = mapPoints[i+1];
CGPoint secondPoint = [self pointForMapPoint:secondMapPoint];

float xDelta = point.x-secondPoint.x;
float yDelta = point.y-secondPoint.y;
float factor = xDelta > 0 ? -1 : 1;

float segmentLength = sqrt(pow(xDelta, 2.0)+pow(yDelta, 2.0));

float yDeltaAngle = asin(sin(M_PI/2*factor)*yDelta/segmentLength);
float opposedAngle = M_PI/2-yDeltaAngle;
float remainingAngle = M_PI/2-opposedAngle;
float yOffset = sin(opposedAngle)*offsetDistance/sin(M_PI/2)*factor;
float xOffset = sin(remainingAngle)*offsetDistance/sin(M_PI/2)*factor;

CGPoint offsetFirstPoint = CGPointMake(point.x+xOffset, point.y+yOffset);
CGPoint offsetSecondPoint = CGPointMake(secondPoint.x+xOffset, secondPoint.y+yOffset);

if(i == mapPointIndex) {
CGPathMoveToPoint(path, NULL, offsetFirstPoint.x, offsetFirstPoint.y);
previousDrawnPoint = offsetFirstPoint;
}
else {
float xNormalDifference = previousEdgeNormal.x-offsetFirstPoint.x;
float yNormalDifference = previousEdgeNormal.y-offsetFirstPoint.y;

float xAverage = (xNormalDifference)/2;
float yAverage = (yNormalDifference)/2;
CGPoint normalAveragePoint = CGPointMake(offsetFirstPoint.x+xAverage, offsetFirstPoint.y+yAverage);

CGPathAddLineToPoint(path, NULL, normalAveragePoint.x, normalAveragePoint.y);
previousDrawnPoint = normalAveragePoint;
}

previousEdgeNormal = offsetSecondPoint;
}
else
CGPathAddLineToPoint(path, NULL, previousEdgeNormal.x, previousEdgeNormal.y);
}
```

，但否则给出一些漂亮的东西(右图是原始路径，左为偏移)