用CALayer画一条线

时间:2014-02-02 19:56:57

标签: objective-c cocoa-touch calayer transformation quartz-core

我正在尝试使用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;,但这段代码无法在屏幕上显示任何线条。我做错了什么

3 个答案:

答案 0 :(得分:32)

试试这个...

-(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];
}

答案 1 :(得分:17)

这是基于Rajesh Choudhary答案的Swift版本:

Swift 2

func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end: CGPoint) {
    let line = CAShapeLayer()
    let linePath = UIBezierPath()
    linePath.moveToPoint(start)
    linePath.addLineToPoint(end)
    line.path = linePath.CGPath
    line.fillColor = nil
    line.opacity = 1.0
    line.strokeColor = UIColor.redColor().CGColor
    layer.addSublayer(line)
}

Swift 3

func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end: CGPoint) {
    let line = CAShapeLayer()
    let linePath = UIBezierPath()
    linePath.move(to: start)
    linePath.addLine(to: end)
    line.path = linePath.cgPath
    line.fillColor = nil
    line.opacity = 1.0
    line.strokeColor = UIColor.red.cgColor
    layer.addSublayer(line)
}

答案 2 :(得分:0)

这是基于Rajesh Choudhary答案的Swift 3版本:

func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end:CGPoint) {
        let line = CAShapeLayer()
        let linePath = UIBezierPath()
        linePath.move(to: start)
        linePath.addLine(to: end)
        line.path = linePath.cgPath
        line.fillColor = nil
        line.opacity = 1.0
        line.strokeColor = UIColor.green.cgColor
        layer.addSublayer(line)
    }