CoreGraphic框架解析 (十五)—— Arcs 和 Paths (二)

版本记录

版本号 时间
V1.0 2019.02.11 星期一

前言

quartz是一个通用的术语,用于描述在iOSMAC OS X 中整个媒体层用到的多种技术 包括图形、动画、音频、适配。Quart 2D 是一组二维绘图和渲染APICore Graphic会使用到这组APIQuartz Core专指Core Animation用到的动画相关的库、API和类。CoreGraphicsUIKit下的主要绘图系统,频繁的用于绘制自定义视图。Core Graphics是高度集成于UIView和其他UIKit部分的。Core Graphics数据结构和函数可以通过前缀CG来识别。在app中很多时候绘图等操作我们要利用CoreGraphic框架,它能绘制字符串、图形、渐变色等等,是一个很强大的工具。感兴趣的可以看我另外几篇。
1. CoreGraphic框架解析(一)—— 基本概览
2. CoreGraphic框架解析(二)—— 基本使用
3. CoreGraphic框架解析(三)—— 类波浪线的实现
4. CoreGraphic框架解析(四)—— 基本架构补充
5. CoreGraphic框架解析 (五)—— 基于CoreGraphic的一个简单绘制示例 (一)
6. CoreGraphic框架解析 (六)—— 基于CoreGraphic的一个简单绘制示例 (二)
7. CoreGraphic框架解析 (七)—— 基于CoreGraphic的一个简单绘制示例 (三)
8. CoreGraphic框架解析 (八)—— 基于CoreGraphic的一个简单绘制示例 (四)
9. CoreGraphic框架解析 (九)—— 一个简单小游戏 (一)
10. CoreGraphic框架解析 (十)—— 一个简单小游戏 (二)
11. CoreGraphic框架解析 (十一)—— 一个简单小游戏 (三)
12. CoreGraphic框架解析 (十二)—— Shadows 和 Gloss (一)
13. CoreGraphic框架解析 (十三)—— Shadows 和 Gloss (二)
14. CoreGraphic框架解析 (十四)—— Arcs 和 Paths (一)

源码

1. Swift

首先看下工程组织结构

1. TutorialsViewController.swift
import UIKit

class TutorialsViewController: UIViewController {
  @IBOutlet var tableView: UITableView!
  
  let viewModel = TutorialsViewModel()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    title = "Learning Agenda" 
    
    tableView.delegate = self
    tableView.dataSource = self
  }
}

extension TutorialsViewController: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    return viewModel.numberOfSections
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return viewModel.numberOfRows(in: section)
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CoolCell", for: indexPath)
    
    if cell.backgroundView?.isKind(of: CustomCellBackground.self) != true {
      cell.backgroundView = CustomCellBackground()
    }
    
    if cell.selectedBackgroundView?.isKind(of: CustomCellBackground.self) != true {
      cell.selectedBackgroundView = CustomCellBackground()
    }
    
    cell.textLabel?.text = viewModel.text(at: indexPath)
    
    return cell
  }
}

extension TutorialsViewController: UITableViewDelegate {
  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 50
  }
  
  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    guard let customHeaderView = CustomHeader.loadViewFromNib() else {
      return nil
    }
    
    customHeaderView.titleLabel.text = self.tableView(tableView, titleForHeaderInSection: section)
    
    if TutorialsViewModel.Section(rawValue: section) == .thingsLearned {
      customHeaderView.startColor = UIColor.rwLightPurple
      customHeaderView.endColor = UIColor.rwDarkPurple
    }
    
    return customHeaderView
  }
  
  func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return viewModel.title(for: section)
  }
  
  func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 30
  }
  
  func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    return CustomFooter()
  }
}
2. CustomCellBackground.swift
import UIKit

class CustomCellBackground: UIView {
  override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()!
    
    context.drawLinearGradient(rect: bounds, startColor: .white, endColor: .rwLightGray)
  }  
}
3. CustomHeader.swift
import UIKit

class CustomHeader: UIView {
  @IBOutlet public var titleLabel: UILabel!
  
  var startColor = UIColor.rwLightBlue
  var endColor = UIColor.rwDarkBlue
  var coloredBoxHeight: CGFloat = 40
  
  override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()!
    
    var coloredBoxRect = bounds
    coloredBoxRect.size.height = coloredBoxHeight
    
    var paperRect = bounds
    paperRect.origin.y += coloredBoxHeight
    paperRect.size.height = bounds.height - coloredBoxHeight
    
    context.saveGState()
    context.setShadow(offset: CGSize(width: 0, height: 2), blur: 3.0, color: UIColor.rwShadow.cgColor)
    context.setFillColor(startColor.cgColor)
    context.fill(coloredBoxRect)
    context.restoreGState()
    
    context.drawGlossAndGradient(rect: coloredBoxRect, startColor: startColor, endColor: endColor)
    context.setStrokeColor(endColor.cgColor)
    context.setLineWidth(1)
    context.stroke(coloredBoxRect.rectFor1PxStroke())
  } 
  
  class func loadViewFromNib() -> CustomHeader? {
    let nib = UINib(nibName: "CustomHeader", bundle: nil)
    return nib.instantiate(withOwner: CustomHeader()).first as? CustomHeader
  }
}
4. Extensions.swift
import UIKit

extension UIColor {
  static let rwShadow = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5)
  static let rwLightGray = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1)
  static let rwDarkGray = UIColor(red: 187/255.0, green: 187/255.0, blue: 187/255.0, alpha: 1)
  static let rwLightBlue = UIColor(red: 105/255.0, green: 179/255.0, blue: 216/255.0, alpha: 1)
  static let rwDarkBlue = UIColor(red: 21/255.0, green: 92/255.0, blue: 136/255.0, alpha: 1)
  static let rwLightPurple = UIColor(red: 147/255.0, green: 105/255.0, blue: 216/255.0, alpha: 1)
  static let rwDarkPurple = UIColor(red: 72/255.0, green: 22/255.0, blue: 137/255.0, alpha: 1)
}

extension CGRect {
  func rectFor1PxStroke() -> CGRect {
    return CGRect(x: origin.x + 0.5, y: origin.y + 0.5, width: size.width - 1, height: size.height - 1)
  }
}

extension CGContext {
  func drawLinearGradient(rect: CGRect, startColor: UIColor, endColor: UIColor) {
    let gradient = CGGradient(colorsSpace: nil, colors: [startColor.cgColor, endColor.cgColor] as CFArray, locations: [0, 1])!
    
    let startPoint = CGPoint(x: rect.midX, y: rect.minY)
    let endPoint = CGPoint(x: rect.midX, y: rect.maxY)
    saveGState()
    addRect(rect)
    clip()
    drawLinearGradient(gradient, start: startPoint, end: endPoint, options: [])    
    restoreGState()
  }
  
  func drawGlossAndGradient(rect: CGRect, startColor: UIColor, endColor: UIColor) {
    drawLinearGradient(rect: rect, startColor: startColor, endColor: endColor)
    
    let glossColor1 = UIColor.white.withAlphaComponent(0.35)
    let glossColor2 = UIColor.white.withAlphaComponent(0.1)
    
    var topHalf = rect
    topHalf.size.height /= 2
    
    drawLinearGradient(rect: topHalf, startColor: glossColor1, endColor: glossColor2)
  }
  
  static func createArcPathFromBottom(of rect: CGRect, arcHeight: CGFloat, startAngle: Angle, endAngle: Angle) -> CGPath {
    // 1
    let arcRect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.height, width: rect.width, height: arcHeight)
    
    // 2
    let arcRadius = (arcRect.height / 2) + pow(arcRect.width, 2) / (8 * arcRect.height)
    let arcCenter = CGPoint(x: arcRect.origin.x + arcRect.width / 2, y: arcRect.origin.y + arcRadius)
    let angle = acos(arcRect.width / (2 * arcRadius))
    let startAngle = CGFloat(startAngle.toRadians()) + angle
    let endAngle = CGFloat(endAngle.toRadians()) - angle
    
    let path = CGMutablePath()
    // 3
    path.addArc(center: arcCenter, radius: arcRadius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
    path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
    path.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
    path.addLine(to: CGPoint(x: rect.minY, y: rect.maxY))
    // 4
    return path.copy()!
  }
}

typealias Angle = Measurement<UnitAngle>

extension Measurement where UnitType == UnitAngle {
  init(degrees: Double) {
    self.init(value: degrees, unit: .degrees)
  }
  
  func toRadians() -> Double {
    return converted(to: .radians).value
  }
}
5. CustomFooter.swift
import UIKit

class CustomFooter: UIView {
  override init(frame: CGRect) {
    super.init(frame: frame)
    
    isOpaque = true
    backgroundColor = .clear
  }
  
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()!
    
    let footerRect = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: bounds.height)
    
    var arcRect = footerRect
    arcRect.size.height = 8
    
    context.saveGState()
    let arcPath = CGContext.createArcPathFromBottom(of: arcRect, arcHeight: 4, startAngle: Angle(degrees: 180), endAngle: Angle(degrees: 360))
    context.addPath(arcPath)
    context.clip()
    
    context.drawLinearGradient(rect: footerRect, startColor: .rwLightGray, endColor: .rwDarkGray)
    context.restoreGState()
    
    context.addRect(footerRect)
    context.addPath(arcPath)
    context.clip(using: .evenOdd)
    context.addPath(arcPath)
    context.setShadow(offset: CGSize(width: 0, height: 2), blur: 3, color: UIColor.rwShadow.cgColor)
    context.fillPath()
  }
}
6. TutorialsViewModel.swift
import Foundation

final class TutorialsViewModel {
  let thingsToLearn = ["Drawing Rects", "Drawing Gradients", "Drawing Arcs"]
  let thingsLearned = ["Table Views", "UIKit", "Swift"]
  
  var numberOfSections: Int {
    return Section.allCases.count
  }
  
  func numberOfRows(in section: Int) -> Int {
    guard let section = Section(rawValue: section) else { return 0 }

    switch section {
    case .thingsToLearn:
      return thingsToLearn.count
    case .thingsLearned:
      return thingsLearned.count
    }
  }
  
  func text(at indexPath: IndexPath) -> String {
    guard let section = Section(rawValue: indexPath.section) else { return "" }

    switch section {
    case .thingsToLearn:
      return thingsToLearn[indexPath.row]
    case .thingsLearned:
      return thingsLearned[indexPath.row]
    }
  }
  
  func title(for section: Int) -> String {
    return Section(rawValue: section)?.description ?? ""
  }
}

extension TutorialsViewModel {
  enum Section: Int, CaseIterable {
    case thingsToLearn
    case thingsLearned
  }
}

extension TutorialsViewModel.Section: CustomStringConvertible {
  var description: String {
    switch self {
    case .thingsToLearn:
      return "Things To Learn"
    case .thingsLearned:
      return "Things Learned"
    }
  }
}

后记

本篇主要讲述了Arcs 和 Paths,感兴趣的给个赞或者关注~~~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容