我试图使用CALayer在两个点之间画一条线。以下是我的代码:
//positions a CALayer to be a line between a parent node and its subnodes.
-(void)makeLineLayer:(CALayer *)layer lineFromPointA:(CGPoint)pointA toPointB:(CGPoint)pointB{
NSLog([NSString stringWithFormat:@"Coordinates: \n Ax: %f Ay: %f Bx: %f By: %f", pointA.x,pointA.y,pointB.x,pointB.y]);
//find the length of the line:
CGFloat length = sqrt((pointA.x - pointB.x) * (pointA.x - pointB.x) + (pointA.y - pointB.y) * (pointA.y - pointB.y));
layer.frame = CGRectMake(0, 0, 1, length);
//calculate and set the layer's center:
CGPoint center = CGPointMake((pointA.x+pointB.x)/2, (pointA.y+pointB.y)/2);
layer.position = center;
//calculate the angle of the line and set the layer's transform to match it.
CGFloat angle = atan2f(pointB.y - pointA.y, pointB.x - pointA.x);
layer.transform = CATransform3DMakeRotation(angle, 0, 0, 1);
}
我知道长度计算正确,而且我相当确定中心点也是正确的。运行程序后,显示的线条长度正确,穿过两点之间的中心点,但旋转方向不正确。起初我认为线条围绕着错误的锚点旋转,所以我尝试了这段代码:layer.anchorPoint = center;
,但这段代码没有在屏幕上显示任何线条。我做错了什么?
layer.anchorPoint = center;
会将锚点设置到很远的地方,旋转就会超出屏幕的范围...这解释了为什么它没有显示。不过,你有任何想法是什么问题吗? - 67cherries