2

I have to draw a shape and detect if user touches are inside the shape or not, so I defined a custom class inherit from UIView as follow :

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()
  }

this code should draw shape like this

shape

  override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let path = UIBezierPath(ovalIn: self.frame)
    return path.contains(point)
  }
}

and in the viewController I wrote this code to add this custom view to 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!)
 }

I knew that the shape is inside the view after wrote this method :

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")  
    }

but overall result was this image it just has one color of the view as green and there's a subview but no color appeared

colored UIView with uncolored shape inside

So what's wrong with this code ?

1
  • 1
    You also might want to call super.draw(rect) in you override func draw(_ rect: CGRect) {} function
    – Bacon
    Commented Jul 14, 2017 at 9:33

1 Answer 1

2

You should use the size of the rect of the override func draw(_ rect: CGRect) to do your calculations on.

I also think your calculations are incorrect, haven't tested it but I think it should be something like this:

ctx.move(to: CGPoint(x: rect.width / 2, y: 0))
ctx.addLine(to: CGPoint(x: rect.width, y: rect.height / 2))
ctx.addLine(to: CGPoint(x: rect.width / 2 , y: rect.height))
ctx.addLine(to: CGPoint(x: 0, y: rect.height / 2))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.