ios - UIGraphicsGetCurrentContext 没有出现在 UIView 中

标签 ios swift uiview core-graphics draw

我必须绘制一个形状并检测用户触摸是否在形状内部,因此我定义了一个继承自 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()
  }

这段代码应该绘制这样的形状

shape

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

在 viewController 中,我编写了以下代码以将此自定义 View 添加到 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!)
 }

写完这个方法后我知道形状在 View 内部:

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

但总体结果是这张图像,它只有一种 View 颜色为绿色,并且有一个 subview ,但没有出现颜色

colored UIView with uncolored shape inside

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

最佳答案

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

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

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

关于ios - UIGraphicsGetCurrentContext 没有出现在 UIView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45098357/

相关文章:

ios - 在 Xcode 10 中添加预处理器宏

Iphone UIView 切换 : Previous view's subviews polluting newly switched-to view

iphone - 如何制作任何 View 的圆形

ios - Swift:将 "addTarget"应用于不同类中的 UIButton

ios - 动画 block 中 UIView 的旋转和设置中心有时不起作用

ios - 如何从低于 xcode 8 的 xcode 查看 iOS 10 日志

ios - iphone 应用程序 : put a toolbar on the top

ios - 找不到架构 arm64 的 IOSurface 框架

ios - iOS 应用程序和子类化中的多个 UITableView Controller

ios - 无法访问自定义 UIView 属性