UIGraphicsGetCurrentContext didn't appear inside UIView

若如初见. 提交于 2020-01-04 13:47:54

问题


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

  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

So what's wrong with this code ?


回答1:


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


来源:https://stackoverflow.com/questions/45098357/uigraphicsgetcurrentcontext-didnt-appear-inside-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!