首页 > 解决方案 > 如何切掉 UIButton 的角,而不是圆角?

问题描述

我想迅速切掉 UIButton 的角落。

我知道如何设置拐角半径,但我想减少拐角。

// what I DON'T want, rounded corners
myButton.layer.cornerRadius = myButton.frame.height / 2

切角适合我:

在此处输入图像描述

标签: swiftuibutton

解决方案


像这样创建具有所需路径的 CAShapeLayer

在此处输入图像描述

let button = UIButton()
button.backgroundColor = .red
button.frame = CGRect(x: 100, y: 100, width: 200, height: 40)
view.addSubview(button)

let layer = CAShapeLayer()
layer.fillColor = UIColor.yellow.cgColor

let cutSize:CGFloat = 20
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: button.bounds.midY))
path.addLine(to: CGPoint(x: cutSize, y: 0))
path.addLine(to: CGPoint(x: button.bounds.maxX-cutSize, y: 0))
path.addLine(to: CGPoint(x: button.bounds.maxX, y: button.bounds.midY))
path.addLine(to: CGPoint(x: button.bounds.maxX-cutSize, y: button.bounds.maxY))
path.addLine(to: CGPoint(x: cutSize, y: button.bounds.maxY))
path.addLine(to: CGPoint(x: 0, y: button.bounds.midY))

layer.path = path.cgPath
button.layer.insertSublayer(layer, at: 0)

推荐阅读