上篇中有提到不规则视图 这里就不再赘述
- 已经画好的UIBezierPath对象marginalPath
2.这里直接在上篇的不规则View上添加了个Button
button.frame = self.bounds button.setBackgroundImage(creatImageWithColor(color: UIColor.red), for: .highlighted)
button.isUserInteractionEnabled = false
重写view的touchBegan和touchEnd方法
在touchBegan中获取到当前手指触摸的点
然后利用UIBezierPath 类中系统提供的contains方法 判断当前触摸点是否在path中,在就把按钮置为高亮 ,触摸结束后按钮取消高亮状态
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch:UITouch = ((touches as NSSet).anyObject()! )as!UITouch
let point = touch.location(in: self)
if marginalPath.contains(point)
{
print("包含")
button.isHighlighted = true
}
else{
print("no")
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
button.isHighlighted = false
}
//生成一张纯色的图片
func creatImageWithColor(color:UIColor)->UIImage{
let rect = CGRect(x:0,y:0,width:1,height:1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}