迅速-按下时为按钮创建径向线

时间:2018-12-19 22:33:40

标签: ios swift uibutton calayer programmatically-created

当我按下按钮7时,我被要求以编程方式创建径向线效果,但不确定要从哪里开始重新创建它。

enter image description here

我猜这是使用CALayer正确完成的吗?我不是在要求代码,但是如果有人可以将我推向正确的方向,那就太好了。

谢谢!

1 个答案:

答案 0 :(得分:1)

当您要绘制一个简单的几何图案时,为什么不直接在代码中绘制呢?这是我渲染的放射状图片:

enter image description here

这是生成它的测试应用程序的完整代码:

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let c1 = UIColor(red: 140/255.0, green: 240/255.0, blue: 209/255.0, alpha: 1)
        let c2 = UIColor(red: 59/255.0, green: 150/255.0, blue: 123/255.0, alpha: 1)
        let iv = UIImageView(image:self.radialLinesImage(
            size:CGSize(width:200, height:200), div:20,
            c1:c1, c2:c2))
        iv.frame.origin = CGPoint(x:100, y:100)
        self.view.addSubview(iv)
    }
    func radialLinesImage(size:CGSize, div:CGFloat, c1:UIColor, c2:UIColor) -> UIImage {
        let r = UIGraphicsImageRenderer(size: size)
        return r.image { ctx in
            c1.setFill()
            ctx.fill(CGRect(origin:.zero, size:size))
            c2.setFill()
            let p = UIBezierPath()
            let c = CGPoint(x:size.width/2, y:size.height/2)
            for i in 0..<Int(div) {
                let a = CGFloat.pi/(div/2) * CGFloat(i)
                p.addArc(withCenter: c,
                         radius: size.width+size.height,
                         startAngle: a, endAngle: a+CGFloat.pi/div,
                         clockwise: true)
                p.addLine(to: c)
                p.fill()
            }
        }
    }
}