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

版本記錄

版本號(hào) 時(shí)間
V1.0 2019.02.12 星期二

前言

quartz是一個(gè)通用的術(shù)語,用于描述在iOSMAC OS X 中整個(gè)媒體層用到的多種技術(shù) 包括圖形、動(dòng)畫、音頻垛吗、適配。Quart 2D 是一組二維繪圖和渲染API烁登,Core Graphic會(huì)使用到這組API怯屉,Quartz Core專指Core Animation用到的動(dòng)畫相關(guān)的庫、API和類饵沧。CoreGraphicsUIKit下的主要繪圖系統(tǒng)蚀之,頻繁的用于繪制自定義視圖。Core Graphics是高度集成于UIView和其他UIKit部分的捷泞。Core Graphics數(shù)據(jù)結(jié)構(gòu)和函數(shù)可以通過前綴CG來識(shí)別。在app中很多時(shí)候繪圖等操作我們要利用CoreGraphic框架寿谴,它能繪制字符串锁右、圖形、漸變色等等,是一個(gè)很強(qiáng)大的工具咏瑟。感興趣的可以看我另外幾篇拂到。
1. CoreGraphic框架解析(一)—— 基本概覽
2. CoreGraphic框架解析(二)—— 基本使用
3. CoreGraphic框架解析(三)—— 類波浪線的實(shí)現(xiàn)
4. CoreGraphic框架解析(四)—— 基本架構(gòu)補(bǔ)充
5. CoreGraphic框架解析 (五)—— 基于CoreGraphic的一個(gè)簡單繪制示例 (一)
6. CoreGraphic框架解析 (六)—— 基于CoreGraphic的一個(gè)簡單繪制示例 (二)
7. CoreGraphic框架解析 (七)—— 基于CoreGraphic的一個(gè)簡單繪制示例 (三)
8. CoreGraphic框架解析 (八)—— 基于CoreGraphic的一個(gè)簡單繪制示例 (四)
9. CoreGraphic框架解析 (九)—— 一個(gè)簡單小游戲 (一)
10. CoreGraphic框架解析 (十)—— 一個(gè)簡單小游戲 (二)
11. CoreGraphic框架解析 (十一)—— 一個(gè)簡單小游戲 (三)
12. CoreGraphic框架解析 (十二)—— Shadows 和 Gloss (一)
13. CoreGraphic框架解析 (十三)—— Shadows 和 Gloss (二)
14. CoreGraphic框架解析 (十四)—— Arcs 和 Paths (一)
15. CoreGraphic框架解析 (十五)—— Arcs 和 Paths (二)
16. CoreGraphic框架解析 (十六)—— Lines, Rectangles 和 Gradients (一)

源碼

1. Swift

首先看下工程組織結(jié)構(gòu)

接著看下sb中的內(nèi)容

下面就是看源碼了。

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码泞,感興趣的給個(gè)贊或者關(guān)注~~~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末兄旬,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子余寥,更是在濱河造成了極大的恐慌领铐,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,123評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件宋舷,死亡現(xiàn)場(chǎng)離奇詭異绪撵,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)祝蝠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,031評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門音诈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人绎狭,你說我怎么就攤上這事细溅。” “怎么了儡嘶?”我有些...
    開封第一講書人閱讀 156,723評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵喇聊,是天一觀的道長。 經(jīng)常有香客問我社付,道長承疲,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,357評(píng)論 1 283
  • 正文 為了忘掉前任鸥咖,我火速辦了婚禮燕鸽,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘啼辣。我一直安慰自己啊研,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,412評(píng)論 5 384
  • 文/花漫 我一把揭開白布鸥拧。 她就那樣靜靜地躺著党远,像睡著了一般。 火紅的嫁衣襯著肌膚如雪富弦。 梳的紋絲不亂的頭發(fā)上沟娱,一...
    開封第一講書人閱讀 49,760評(píng)論 1 289
  • 那天,我揣著相機(jī)與錄音腕柜,去河邊找鬼济似。 笑死矫废,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的砰蠢。 我是一名探鬼主播蓖扑,決...
    沈念sama閱讀 38,904評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼台舱!你這毒婦竟也來了律杠?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,672評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤竞惋,失蹤者是張志新(化名)和其女友劉穎柜去,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體碰声,經(jīng)...
    沈念sama閱讀 44,118評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡诡蜓,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,456評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了胰挑。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蔓罚。...
    茶點(diǎn)故事閱讀 38,599評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖瞻颂,靈堂內(nèi)的尸體忽然破棺而出豺谈,到底是詐尸還是另有隱情,我是刑警寧澤贡这,帶...
    沈念sama閱讀 34,264評(píng)論 4 328
  • 正文 年R本政府宣布茬末,位于F島的核電站,受9級(jí)特大地震影響盖矫,放射性物質(zhì)發(fā)生泄漏丽惭。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,857評(píng)論 3 312
  • 文/蒙蒙 一辈双、第九天 我趴在偏房一處隱蔽的房頂上張望责掏。 院中可真熱鬧,春花似錦湃望、人聲如沸换衬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,731評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽瞳浦。三九已至,卻和暖如春废士,著一層夾襖步出監(jiān)牢的瞬間叫潦,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,956評(píng)論 1 264
  • 我被黑心中介騙來泰國打工官硝, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留诅挑,地道東北人四敞。 一個(gè)月前我還...
    沈念sama閱讀 46,286評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像拔妥,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子达箍,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,465評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容