objective-c – 用CALayer画一条线

我试图用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];
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...