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 部分也都是可以通过的。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,148评论 1 32
  • 前言 本文只要描述了iOS中的Core Animation(核心动画:隐式动画、显示动画)、贝塞尔曲线、UIVie...
    GitHubPorter阅读 3,663评论 7 11
  • 知名IT记者刘韧涉嫌金融诈骗 受害者挤满公安局大堂 综合 2017-04-29 20:33 文章来源:红色参考公众...
    曝光时代阅读 284评论 0 0
  • “我们今天所传承的遗产比此前任何时候都更为丰富。它比伯里克利的丰富,因为包含了他以后的希腊文化精华;比达芬奇的丰富...
    gyl58365阅读 215评论 0 0
  • 文:zero007 2018年11月7日 星期三 阴 今日立冬,冬季至此开始。 秋很识时务地收藏起了自己的成熟和丰...
    zero007阅读 629评论 7 10