drawing dashed line using CALayer

后端 未结 8 1415
执笔经年
执笔经年 2020-12-04 16:49

I was able to draw a dashed box, using the following code:

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
CGRect shapeRect = CGRectMake(0.0f, 0.0f, 200.0f,         


        
8条回答
  •  我在风中等你
    2020-12-04 17:44

    Lines are drawn by first moving the path to a starting point of the line, then adding a line segment to a point:

    CGContextBeginPath(context);
    CGContextMoveToPoint(context, 10.5f, 10.5f);
    CGContextAddLineToPoint(context, 20.5f, 20.5f);
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke);
    

    For drawing dashed line, You need to use CAShapeLayer

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:self.bounds];
    [shapeLayer setPosition:self.center];
    [shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
    [shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
    [shapeLayer setLineWidth:3.0f];
    [shapeLayer setLineJoin:kCALineJoinRound];
    [shapeLayer setLineDashPattern:
     [NSArray arrayWithObjects:[NSNumber numberWithInt:10],
      [NSNumber numberWithInt:5],nil]];
    
    // Setup the path
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 10, 10);
    CGPathAddLineToPoint(path, NULL, 100,100);
    
    [shapeLayer setPath:path];
    CGPathRelease(path);
    
    [[self layer] addSublayer:shapeLayer];
    

提交回复
热议问题