UIBezierPath 和 CGPath

UIBezierPathCGPath 的一层封装,以下代码效果是一样的,都创建了一个红底黑边的圆形:

let imageFromBezierPath: UIImage = {
          let rect = CGRect(x: 0.0, y: 0.0, width: 12.0, height: 12.0)
          UIGraphicsBeginImageContext(rect.size)
          let context = UIGraphicsGetCurrentContext()!

          let path = UIBezierPath(ovalIn: rect)
          UIColor.red.setFill()
          path.fill()
          assert(context.path == nil)

          UIColor.black.setStroke()
          path.stroke()
          assert(context.path == nil)

          let image = UIGraphicsGetImageFromCurrentImageContext()!
          UIGraphicsEndImageContext()

          return image
        }()
let imageFromCGPath: UIImage = {
          let rect = CGRect(x: 0.0, y: 0.0, width: 12.0, height: 12.0)
          UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)

          let context = UIGraphicsGetCurrentContext()!

          let path = CGPath(ellipseIn: rect, transform: nil)

          assert(context.path == nil)
          context.addPath(path)
          assert(context.path != nil)
          context.setFillColor(UIColor.red.cgColor)
          context.fillPath()
          assert(context.path == nil)

          context.addPath(path)
          assert(context.path != nil)
          context.setStrokeColor(UIColor.black.cgColor)
          context.strokePath()
          assert(context.path == nil)

          let image = UIGraphicsGetImageFromCurrentImageContext()!
          UIGraphicsEndImageContext()

          return image
        }()

UIBezierPath 常常出现在 UIViewdraw(_:) 方法里,因为 UIKit 会默认创建好一个 CGContext 对象故而不需要另外调用 UIGraphicsBeginImageContextWithOptions()
注意 assert 部分也都是可以通过的。

你可能感兴趣的:(UIBezierPath 和 CGPath)