我必须绘制一个形状并检测用户触摸是否在形状内部,所以我定义了一个从UIView继承的自定义类,如下所示:
class ShapeView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
drawShape()
}
func drawShape() {
guard let ctx = UIGraphicsGetCurrentContext() else { return }
let zero = CGPoint(x: frame.midX, y: frame.midY)
let size: CGFloat = 50
ctx.beginPath()
ctx.move(to: .zero)
ctx.addLine(to: CGPoint(x: -size, y: -size))
ctx.addLine(to: CGPoint(x: zero.x , y: (-size * 2)))
ctx.addLine(to: CGPoint(x: size, y: -size))
ctx.closePath()
ctx.setFillColor(UIColor.red.cgColor)
ctx.fillPath()
}
此代码应该像这样绘制
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
let path = UIBezierPath(ovalIn: self.frame)
return path.contains(point)
}
}
在viewController中我编写了这段代码,将这个自定义视图添加到UIViewController:
var shape: ShapeView?
override func viewDidLoad() {
super.viewDidLoad()
let x = view.frame.midX
let y = view.frame.midY
self.shape = ShapeView(frame: CGRect(x: x, y: y, width: 100, height: 100))
shape?.backgroundColor = .green
view.addSubview(shape!)
}
在写完这个方法后,我知道形状在视图内:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let location = touches.first!.location(in: self.view)
if (shape?.point(inside: location, with: event))! {
print("inside view")
} else {
print("outside view")
}
但总体结果是这个图像只有一种颜色的视图为绿色,并且有一个子视图但没有出现颜色
这个代码有什么问题?
答案 0 :(得分:2)
您应该使用rect
的{{1}}的大小来进行计算。
我也认为你的计算不正确,没有经过测试,但我认为它应该是这样的:
override func draw(_ rect: CGRect)