An easy way to draw a circle using CAShapeLayer

后端 未结 2 1893
梦如初夏
梦如初夏 2020-12-25 12:29

In questions like How to draw a smooth circle..., ...Draw Circle... and ...draw filled Circles the question and answer is very broad, contains lots of unnecessary steps and

相关标签:
2条回答
  • 2020-12-25 12:31

    Using CAShapeLayer Class makes drawing easy... 1.Create CAShapeLayer Object 2.Create a Circular path 3.Set the path to the wanted CAShapeLayer path 4.Add the layer to your view

      let shapeLayer = CAShapeLayer()
      let center = view.center
      let circulPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: 0, endAngle: 2.0 * CGFloat.pi, clockwise: true)
    
      shapeLayer.path = circulPath.cgPath 
      view.layer.addSublayer(shapeLayer)
    

    Note That ,here I draw the circle from center of the view. You can also set the fill color for your circle like bellow:

      shapeLayer.fillColor = UIColor.red.cgColor
    

    for further study you can check on CALayer.com

    0 讨论(0)
  • 2020-12-25 12:47

    An easy way to draw a circle is to create a CAShapeLayer and add a UIBezierPath.

    objective-c

    CAShapeLayer *circleLayer = [CAShapeLayer layer];
    [circleLayer setPath:[[UIBezierPath bezierPathWithOvalInRect:CGRectMake(50, 50, 100, 100)] CGPath]];
    

    swift

    let circleLayer = CAShapeLayer();
    circleLayer.path = UIBezierPath(ovalIn: CGRect(x: 50, y: 50, width: 100, height: 100)).cgPath;
    

    After creating the CAShapeLayer we set its path to be a UIBezierPath.

    Our UIBezierPath then draws a bezierPathWithOvalInRect. The CGRect we set will effect its size and position.

    Now that we have our circle, we can add it to our UIView as a sublayer.

    objective-c

    [[self.view layer] addSublayer:circleLayer];
    

    swift

    view.layer.addSublayer(circleLayer)
    

    Our circle is now visible in our UIView.

    Circle

    If we wish to customise our circle's color properties we can easily do so by setting the CAShapeLayer's stroke- and fill color.

    objective-c

    [circleLayer setStrokeColor:[[UIColor redColor] CGColor]];
    [circleLayer setFillColor:[[UIColor clearColor] CGColor]];
    

    swift

    shapeLayer.strokeColor = UIColor.red.cgColor;
    shapeLayer.fillColor = UIColor.clear.cgColor;
    

    Circle_wColors

    Additionall properties can be found over at 's documentation on the subject https://developer.apple.com/.../CAShapeLayer_class/index.html.

    0 讨论(0)
提交回复
热议问题