我试图用CALayer在两点之间画一条线.这是我的代码:
//将CALayer定位为父节点及其子节点之间的一行.
-(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,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,1); }
我知道这个长度是正确计算的,我很确定中心也是.当我运行时,显示的线条是正确的长度,并且穿过两点之间的中心点,但不能正确旋转.起初我以为这条线被旋转错误的锚点,所以我做了:layer.anchorPoint = center;但是这个代码无法在屏幕上显示任何行.我究竟做错了什么
解决方法
尝试这个…
-(void)makeLineLayer:(CALayer *)layer lineFromPointA:(CGPoint)pointA toPointB:(CGPoint)pointB { CAShapeLayer *line = [CAShapeLayer layer]; UIBezierPath *linePath=[UIBezierPath bezierPath]; [linePath moveToPoint: pointA]; [linePath addLineToPoint:pointB]; line.path=linePath.CGPath; line.fillColor = nil; line.opacity = 1.0; line.strokeColor = [UIColor redColor].CGColor; [layer addSublayer:line]; }