ios 自定义不规则按钮

有两种方式,使按钮只在不规则区域有点击事件

1、按钮放图片,取图片的色值,类似PS中的颜色通道,参考:OBShapedButton,调用如下:

        let button = OBShapedButton()
        button.frame = CGRect(x: 20, y: 150, width: 100, height: 100)
        button.setImage(UIImage(named: "login_logo"), for: .normal)
        button.addTarget(self, action: #selector(onClick), for: .touchUpInside)
        button.backgroundColor = UIColor.red
        self.view.addSubview(button)

2、自定义按钮,可以通过绘制不规则图形,并将判断不规则区域,通过路径来划分


class CustomButton: UIButton {

    private var path: UIBezierPath?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //设置背景色为透明,否则是黑色背景
        self.backgroundColor = UIColor.clear
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)

        let finalSize = CGSize(width:self.bounds.size.width, height:self.bounds.size.height)
       
        let layer = CAShapeLayer()
        let bezier = UIBezierPath()
        bezier.move(to: CGPoint(x: finalSize.width/2.0, y: finalSize.height))
        bezier.addArc(withCenter: CGPoint(x: finalSize.width/2.0, y: finalSize.height),
                      radius: 180, startAngle: (CGFloat(M_PI+M_PI_2*2/3.0)), endAngle: (CGFloat(M_PI+M_PI_2 + M_PI_2/3.0)), clockwise: true)
        bezier.addArc(withCenter: CGPoint(x: finalSize.width/2.0, y: finalSize.height),
                      radius: 50, startAngle: (CGFloat(M_PI+M_PI_2 + M_PI_2/3.0)), endAngle: (CGFloat(M_PI+M_PI_2*2/3.0)), clockwise: false)
        bezier.close()
        layer.path = bezier.cgPath
        layer.fillColor = UIColor.black.cgColor
        self.layer.addSublayer(layer)
        self.path = bezier
    }
    
    // 重写点击判定方法
    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        if path != nil {
            return path!.contains(point)
        }else {
            return super.point(inside: point, with: event)
        }
    }
}

调用:

        let v = CustomButton()
        v.backgroundColor = UIColor.blue
        v.frame = CGRect(x: 50, y: 330, width: 200, height: 200)
        v.addTarget(self, action: #selector(onClick), for: .touchUpInside)
        self.view.addSubview(v)


    @objc func onClick() {
        print("点击了")
    }

猜你喜欢

转载自blog.csdn.net/weixin_40873814/article/details/81214813