加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 用CALayer画一条线

发布时间:2020-12-16 05:41:57 所属栏目:百科 来源:网络整理
导读:我试图用CALayer在两点之间画一条线.这是我的代码: //将CALayer定位为父节点及其子节点之间的一行. -(void)makeLineLayer:(CALayer *)layer lineFromPointA:(CGPoint)pointA toPointB:(CGPoint)pointB{ NSLog([NSString stringWithFormat:@"Coordinates: n
我试图用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];
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读