UIGraphicsGetCurrentContext 没有出现在 UIView 里面

UIGraphicsGetCurrentContext didn't appear inside UIView

我必须绘制一个形状并检测用户触摸是否在形状内部,所以我定义了一个自定义 class 从 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")  
    }

但总体结果是这张图片,它只有一种视图颜色为绿色,还有一个子视图,但没有颜色出现

那么这段代码有什么问题?

您应该使用 rectoverride func draw(_ rect: CGRect) 的大小来进行计算。

我也认为你的计算不正确,没有测试过,但我认为应该是这样的:

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