How to draw stars using Quartz Core?

前端 未结 3 2154
北恋
北恋 2020-12-28 10:29

I\'m trying to adapt an example provided by Apple in order to programmatically draw stars in line, the code is the following:

CGContextRef context = UIGraphi         


        
3条回答
  •  旧巷少年郎
    2020-12-28 10:42

    I prefer using a CAShaperLayer to implementing drawRect, as it can then be animated. Here's a function that will create a path in the shape of a 5 point star:

    func createStarPath(size: CGSize) -> CGPath {
        let numberOfPoints: CGFloat = 5
    
        let starRatio: CGFloat = 0.5
    
        let steps: CGFloat = numberOfPoints * 2
    
        let outerRadius: CGFloat = min(size.height, size.width) / 2
        let innerRadius: CGFloat = outerRadius * starRatio
    
        let stepAngle = CGFloat(2) * CGFloat(M_PI) / CGFloat(steps)
        let center = CGPoint(x: size.width / 2, y: size.height / 2)
    
        let path = CGPathCreateMutable()
    
        for i in 0..

    It can then be used with a CAShapeLayer like so:

    let layer = CAShapeLayer()
    layer.path = createStarPath(CGSize(width: 100, height: 100))
    layer.lineWidth = 1
    layer.strokeColor = UIColor.blackColor().CGColor
    layer.fillColor = UIColor.yellowColor().CGColor
    layer.fillRule = kCAFillRuleNonZero
    

提交回复
热议问题