[英]How to create particular shape for Button by using UIBezierPath as shown in below Attached Image with Swift Code?
I tried with many ways to draw buttons as shown in image, But I'm able to draw only hexagonal . 我尝试了多种方法来绘制按钮,如图所示,但是我只能绘制六边形。 Am not able to draw as show in image .
无法如图片所示绘制。 Please help me how to draw as shown in image.
请帮助我如何绘制如图所示。 Thank you
谢谢
You can do this with UIBezierPath
and CAShapeLayer
您可以使用
UIBezierPath
和CAShapeLayer
进行此CAShapeLayer
Create a UIButton
subclass and override layoutSubviews()
, which is where you'll update your path, connecting the points with lines. 创建一个
UIButton
子类,并覆盖layoutSubviews()
,在该处您将更新路径,将点与线连接起来。
Here is a starting point for you: 这是您的起点:
class AngledButton: UIButton {
var bPath = UIBezierPath()
var theShapeLayer = CAShapeLayer()
var fillColor: UIColor = UIColor.white
var borderColor: UIColor = UIColor.gray
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() -> Void {
layer.addSublayer(theShapeLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
let p1 = CGPoint.zero
let p2 = CGPoint(x: bounds.width - bounds.height * 0.3, y: 0.0)
let p3 = CGPoint(x: bounds.width, y: bounds.height * 0.5)
let p4 = CGPoint(x: bounds.width - bounds.height * 0.3, y: bounds.height)
let p5 = CGPoint(x: 0.0, y: bounds.height)
bPath.move(to: p1)
bPath.addLine(to: p2)
bPath.addLine(to: p3)
bPath.addLine(to: p4)
bPath.addLine(to: p5)
bPath.close()
theShapeLayer.path = bPath.cgPath
theShapeLayer.fillColor = self.fillColor.cgColor
theShapeLayer.strokeColor = self.borderColor.cgColor
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// only allow tap *within* the bezier path
if bPath.contains(point) {
return self
}
return nil
}
}
By also overriding hitTest()
the button will only be tapped if the tap is within the bezier path area. 通过也覆盖
hitTest()
,只有在点击位于贝塞尔曲线路径区域内时,才会轻击按钮。 You can then overlap your buttons, and a tap at the upper-right corner will "pass through" to the button underneath. 然后,您可以重叠按钮,并且单击右上角的水龙头将“通过”下面的按钮。
Result: 结果:
Notes: 笔记:
@IBDesignable
to see the layout in Interface Builder @IBDesignable
成为Interface Builder中的布局
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.