CoreGraphic框架解析 (十七)—— Lines, Rectangles 和 Gradients (二)

版本记录

版本号 时间
V1.0 2019.02.12 星期二

前言

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 (一)
15. CoreGraphic框架解析 (十五)—— Arcs 和 Paths (二)
16. CoreGraphic框架解析 (十六)—— Lines, Rectangles 和 Gradients (一)

源码

1. Swift

首先看下工程组织结构

接着看下sb中的内容

下面就是看源码了。

1. AppDelegate.swift
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
  var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let splitViewController = window!.rootViewController as! UISplitViewController
    let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
    navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
    splitViewController.delegate = self

    // Theming
    UINavigationBar.appearance().tintColor = .starwarsYellow
    UINavigationBar.appearance().barTintColor = .starwarsSpaceBlue
    UINavigationBar.appearance().titleTextAttributes = [.foregroundColor: UIColor.starwarsStarshipGrey]

    return true
  }

  // MARK: - Split view

  func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
      guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
      guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
      if topAsDetailController.starshipItem == nil {
          // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
          return true
      }
      return false
  }
}
2. CGContextExtensions.swift
import UIKit

extension CGContext {
  func drawLinearGradient(
    in rect: CGRect,
    startingWith startColor: CGColor,
    finishingWith endColor: CGColor
    ) {
    let colorSpace = CGColorSpaceCreateDeviceRGB()

    let locations = [0.0, 1.0] as [CGFloat]

    let colors = [startColor, endColor] as CFArray

    guard let gradient = CGGradient(
      colorsSpace: colorSpace,
      colors: colors,
      locations: locations
      ) else {
        return
    }

    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: CGGradientDrawingOptions()
    )

    restoreGState()
  }
}
3. DetailViewController.swift
import UIKit

enum FieldsToDisplay: String, CaseIterable {
  case image = "Image"
  case model = "Model"
  case starshipClass = "Class"
  case costInCredits = "Cost in Credits"
  case cargoCapacity = "Cargo Capacity"
  case MGLT = "Speed"
  case maxAtmospheringSpeed = "Max Atmosphering Speed"
  case length = "Length"
}

class DetailViewController: UITableViewController {
  let numberOfFields = FieldsToDisplay.allCases.count
  let numberFormatter = NumberFormatter()

  lazy var imageFetcher = StarshipImageFetcher()
  
  var starshipImage = UIImage(named: "image_not_found.png")
  var starshipItem: Starship? {
    didSet {
      starshipImage = imageFetcher.imageForStarship(named: starshipItem!.name)
      tableView.reloadData()
    }
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    
    numberFormatter.minimumFractionDigits = 2
    numberFormatter.roundingMode = .halfDown
    
    tableView.rowHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = 375
  }


  // MARK: - UITableViewDataSource
  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return numberOfFields
  }

  override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    if section == 0 {
      return starshipItem?.name
    } else {
      return ""
    }
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if indexPath.row == 0 {
      // The first item is the image, which should be treated differently
      let cell = tableView.dequeueReusableCell(withIdentifier: "ImageCell", for: indexPath) as! StarshipImageCell
      cell.starshipImageView.image = starshipImage
      return cell
    } else {
      let cell = tableView.dequeueReusableCell(withIdentifier: "FieldCell", for: indexPath)

      switch indexPath.row {
      case 1:
        cell.textLabel!.text = FieldsToDisplay.model.rawValue
        cell.detailTextLabel!.text = starshipItem?.model
      case 2:
        cell.textLabel!.text = FieldsToDisplay.starshipClass.rawValue
        cell.detailTextLabel!.text = starshipItem?.starshipClass
      case 3:
        cell.textLabel!.text = FieldsToDisplay.costInCredits.rawValue
        if let cost = starshipItem?.costInCredits,
          let costStr = numberFormatter.string(from: NSNumber(value: cost)) {
          cell.detailTextLabel!.text = "\(costStr)"
        } else {
          cell.detailTextLabel!.text = "Unknown"
        }
      case 4:
        cell.textLabel!.text = FieldsToDisplay.cargoCapacity.rawValue
        if let cargoCapacity = starshipItem?.cargoCapacity,
          let cargoCapacityStr = numberFormatter.string(from: NSNumber(value: cargoCapacity)) {
          cell.detailTextLabel!.text = "\(cargoCapacityStr) kg"
        } else {
          cell.detailTextLabel!.text = "Unknown"
        }
      case 5:
        cell.textLabel!.text = FieldsToDisplay.MGLT.rawValue
        if let MGLT = starshipItem?.MGLT {
          cell.detailTextLabel!.text = "\(MGLT) megalights"
        } else {
          cell.detailTextLabel!.text = "Unknown"
        }
      case 6:
        cell.textLabel!.text = FieldsToDisplay.maxAtmospheringSpeed.rawValue
        if let maxAtmospheringSpeed = starshipItem?.maxAtmospheringSpeed {
          cell.detailTextLabel!.text = "\(maxAtmospheringSpeed)"
        } else {
          cell.detailTextLabel!.text = "Not Applicable"
        }
      case 7:
        cell.textLabel!.text = FieldsToDisplay.length.rawValue
        if let length = starshipItem?.length,
          let lengthStr = numberFormatter.string(from: NSNumber(value: length)) {
          cell.detailTextLabel!.text = "\(lengthStr)"
        } else {
          cell.detailTextLabel!.text = "Unknown"
        }
      default:
        print("Warning! Unexpected row number: \(indexPath.row)")
      }

      cell.textLabel!.textColor = .starwarsStarshipGrey
      cell.detailTextLabel!.textColor = .starwarsYellow

      return cell
    }
  }

  override func tableView(
    _ tableView: UITableView,
    willDisplayHeaderView view: UIView,
    forSection section: Int
    ) {
    view.tintColor = .starwarsYellow
    if let header = view as? UITableViewHeaderFooterView {
      header.textLabel?.textColor = .starwarsSpaceBlue
    }
  }

  // MARK: - UITableViewDelegate
  override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == 0 {
      let widthOfTableView = self.tableView!.frame.width
      let widthOfImage = starshipImage!.size.width
      let scaleFactor = widthOfTableView / widthOfImage
      return starshipImage!.size.height * scaleFactor
    } else {
      return 44.0
    }
  }
}

class StarshipImageCell: UITableViewCell {
  @IBOutlet weak var starshipImageView: UIImageView!
}
4. MasterViewController.swift
import UIKit

class MasterViewController: UITableViewController {
  var detailViewController: DetailViewController?
  var starships: [Starship] = []
  lazy var dataProvider = StarshipDataProvider()
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    if let split = splitViewController {
      let controllers = split.viewControllers
      detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
    }

    tableView.backgroundColor = .starwarsSpaceBlue
  }
  
  override func viewWillAppear(_ animated: Bool) {
    reloadData()
    clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed
    super.viewWillAppear(animated)
  }
  
  func reloadData() {
    starships = dataProvider.fetchAll()
    tableView.reloadData()
  }
  
  // MARK: - Segues
  
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier != "showDetail" {
      return
    }
    
    if let indexPath = tableView.indexPathForSelectedRow {
      let starship = starships[indexPath.row]
      let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
      controller.starshipItem = starship
      controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
      controller.navigationItem.leftItemsSupplementBackButton = true
    }
  }

  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return starships.count
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    if (
      cell.backgroundView == nil ||
        !(cell.backgroundView is StarshipsListCellBackground)
      ) {
      cell.backgroundView = StarshipsListCellBackground()
    }

    if (
      cell.selectedBackgroundView == nil ||
        !(cell.selectedBackgroundView is StarshipsListCellBackground)
      ) {
      cell.selectedBackgroundView = StarshipsListCellBackground()
    }

    let starship = starships[indexPath.row]
    cell.textLabel!.text = starship.name
    cell.textLabel!.textColor = .starwarsStarshipGrey
    
    return cell
  }

  override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    return false
  }
}
5. Starship.swift
import Foundation

struct Starship: Decodable {
  let name: String
  let model: String
  let starshipClass: String
  let costInCredits: Float!
  let cargoCapacity: Float!
  let MGLT: Int!
  let maxAtmospheringSpeed: Int!
  let length: Float
}

struct Node: Decodable  {
  let starship: Starship
  
  enum CodingKeys: String, CodingKey {
    case starship = "node"
  }
}

struct AllStarships: Decodable {
  let starships: [Node]
  
  enum CodingKeys: String, CodingKey {
    case starships = "allStarships"
  }
}
6. StarshipDataProvider.swift
import Foundation

// The data stored in Starship.json is a lightly modified response from the Star Wars API example from GraphQL - https://graphql.org/swapi-graphql
// Full query: https://goo.gl/ngGGFA
class StarshipDataProvider {
  func fetchAll() -> [Starship] {
    let url = Bundle.main.url(forResource: "Starships", withExtension: "json")!
    do {
      let data = try Data(contentsOf: url)
      let allStarships = try JSONDecoder().decode(AllStarships.self, from: data)
      return allStarships.starships.map { $0.starship }
    }
    catch {
      print("Could not decode starship data from JSON")
      print(error)
      return []
    }
  }
}
7. StarshipImageFetcher.swift
import UIKit

class StarshipImageFetcher {
  func imageForStarship(named name: String) -> UIImage? {
    let imageName = name.lowercased().replacingOccurrences(of: " ", with: "_")
    if let image = UIImage(named: "\(imageName).png") {
      return  image
    } else {
      return UIImage(named: "image_not_found.png")
    }
  }
}
8. StarshipsListCellBackground.swift
import UIKit

class StarshipsListCellBackground: UIView {
  override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else {
      return
    }
    let backgroundRect = bounds
    context.drawLinearGradient(
      in: backgroundRect,
      startingWith: UIColor.starwarsSpaceBlue.cgColor,
      finishingWith: UIColor.black.cgColor
    )
    
    let strokeRect = backgroundRect.insetBy(dx: 4.5, dy: 4.5)
    context.setStrokeColor(UIColor.starwarsYellow.cgColor)
    context.setLineWidth(1)
    context.stroke(strokeRect)
  }
}
9. StarshipTableView.swift
import UIKit

class StarshipTableView: UITableView {
  override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else {
      return
    }

    let backgroundRect = self.bounds
    context.drawLinearGradient(
      in: backgroundRect,
      startingWith: UIColor.starwarsSpaceBlue.cgColor,
      finishingWith: UIColor.black.cgColor
    )
  }
}
10. UIColorExtensions.swift
import UIKit

extension UIColor {
  public static let starwarsYellow =
    UIColor(red: 250/255, green: 202/255, blue: 56/255, alpha: 1.0)
  public static let starwarsSpaceBlue =
    UIColor(red: 5/255, green: 10/255, blue: 85/255, alpha: 1.0)
  public static let starwarsStarshipGrey =
    UIColor(red: 159/255, green: 150/255, blue: 135/255, alpha: 1.0)
} 
11. YellowSplitterTableViewCell.swift
import UIKit

class YellowSplitterTableViewCell: UITableViewCell {
  override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else {
      return
    }

    let y = bounds.maxY - 0.5
    let minX = bounds.minX
    let maxX = bounds.maxX

    // Draw the line
    context.setStrokeColor(UIColor.starwarsYellow.cgColor)
    context.setLineWidth(1.0)
    context.move(to: CGPoint(x: minX, y: y))
    context.addLine(to: CGPoint(x: maxX, y: y))
    context.strokePath()
  }
}

后记

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

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

推荐阅读更多精彩内容