CoreGraphic框架解析 (二十九) —— 關於線、矩形和漸變的繪製(二) 版本記錄 前言 源碼 後記

版本記錄

版本號 時間
V1.0 2021.09.04 星期六

前言

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 (一)
17. CoreGraphic框架解析 (十七)—— Lines, Rectangles 和 Gradients (二)
18. CoreGraphic框架解析 (十八) —— 如何製作Glossy效果的按鈕(一)
19. CoreGraphic框架解析 (十九) —— 如何製作Glossy效果的按鈕(二)
20. CoreGraphic框架解析 (二十) —— Curves and Layers(一)
21. CoreGraphic框架解析 (二十一) —— Curves and Layers(二)
22. CoreGraphic框架解析 (二十二) —— Gradients 和 Contexts的簡單示例(一)
23. CoreGraphic框架解析 (二十三) —— Gradients 和 Contexts的簡單示例(二)
24. CoreGraphic框架解析 (二十四) —— 基於Core Graphic的重複圖案的繪製(一)
25. CoreGraphic框架解析 (二十五) —— 基於Core Graphic的重複圖案的繪製(二)
26. CoreGraphic框架解析 (二十六) —— 以高效的方式繪製圖案(一)
27. CoreGraphic框架解析 (二十七) —— 以高效的方式繪製圖案(二)
28. CoreGraphic框架解析 (二十八) —— 關於線、矩形和漸變的繪製(一)

源碼

1. Swift

首先看下工程組織結構。

下面就是源碼了

1. AppDelegate.swift
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
    let barAppearance = UINavigationBarAppearance()
    barAppearance.configureWithOpaqueBackground()
    barAppearance.backgroundColor = .starwarsSpaceBlue
    barAppearance.titleTextAttributes = [.foregroundColor: UIColor.starwarsStarshipGrey]

    UINavigationBar.appearance().tintColor = .starwarsYellow
    UINavigationBar.appearance().barStyle = .black
    UINavigationBar.appearance().standardAppearance = barAppearance
    UINavigationBar.appearance().scrollEdgeAppearance = barAppearance
    return true
  }
}
2. SceneDelegate.swift
import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
  var window: UIWindow?
}
3. StarshipListCell.swift
import UIKit

class StarshipListCell: UITableViewCell {
  override func awakeFromNib() {
    super.awakeFromNib()
    backgroundView = StarshipListCellBackground()
  }
}
4. StarshipImageCell.swift
import UIKit

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

class StarshipFieldCell: 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

    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()
  }
}
6. StarshipListCellBackground.swift
import UIKit

class StarshipListCellBackground: UIView {
  override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else {
      return
    }
    context.drawLinearGradient(
      in: bounds,
      startingWith: UIColor.starwarsSpaceBlue.cgColor,
      finishingWith: UIColor.black.cgColor)

    let strokeRect = bounds.insetBy(dx: 4.5, dy: 4.5)
    context.setStrokeColor(UIColor.starwarsYellow.cgColor)
    context.setLineWidth(1)
    context.stroke(strokeRect)
  }
}
7. StarshipTableView.swift
import UIKit

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

    context.drawLinearGradient(
      in: bounds,
      startingWith: UIColor.starwarsSpaceBlue.cgColor,
      finishingWith: UIColor.black.cgColor)
  }
}
8. StarshipsViewController.swift
import UIKit

class StarshipsViewController: UITableViewController {
  let starships = Starship.all

  override func viewDidLoad() {
    super.viewDidLoad()
    tableView.separatorStyle = .none
    tableView.backgroundColor = .starwarsSpaceBlue
  }

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let controller = segue.destination as? StarshipDetailViewController else {
      return
    }
    controller.starship = sender as? Starship
  }
}

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

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(
      withIdentifier: "ListCell", for: indexPath) as? StarshipListCell else {
      return UITableViewCell()
    }

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

  override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let starship = starships[indexPath.row]
    performSegue(withIdentifier: "showDetail", sender: starship)
  }
}
9. StarshipDetailViewController.swift
import UIKit

class StarshipDetailViewController: UITableViewController {
  var starship: Starship? {
    didSet {
      populateTableItems()
    }
  }
  var tableItems: [StarshipDetailTableItem] = []

  let numberFormatter: NumberFormatter = {
    let formatter = NumberFormatter()
    formatter.minimumFractionDigits = 2
    formatter.roundingMode = .halfDown
    return formatter
  }()

  override func viewDidLoad() {
    super.viewDidLoad()
    tableView.rowHeight = UITableView.automaticDimension
    tableView.estimatedRowHeight = 44.0
  }
}

extension StarshipDetailViewController {
  func populateTableItems() {
    tableItems = []
    guard let starship = self.starship else {
      return
    }

    if let image = starship.image {
      tableItems.append(.image(image))
    }
    tableItems.append(.field("Model", starship.model))
    tableItems.append(.field("Class", starship.starshipClass))

    if let costInCredits = starship.costInCredits,
    let formattedCost = numberFormatter.string(from: NSNumber(value: costInCredits)) {
      tableItems.append(.field("Cost in Credits", formattedCost))
  } else {
    tableItems.append(.field("Cost in Credits", "Unknown"))
  }

    if let capacity = starship.cargoCapacity,
    let formattedCapacity = numberFormatter.string(from: NSNumber(value: capacity)) {
      tableItems.append(.field("Cargo Capacity", "\(formattedCapacity) kg"))
    } else {
      tableItems.append(.field("Cargo Capacity", "Unknown"))
    }

    if let mglt = starship.MGLT {
      tableItems.append(.field("Speed", "\(mglt) megalights"))
    } else {
      tableItems.append(.field("Speed", "Unknown"))
    }

    if let aSpeed = starship.maxAtmospheringSpeed {
      tableItems.append(.field("Max Atmosphering Speed", "\(aSpeed)"))
    } else {
      tableItems.append(.field("Max Atmosphering Speed", "Not Applicable"))
    }

    if let length = numberFormatter.string(from: NSNumber(value: starship.length)) {
      tableItems.append(.field("Length", "\(length)"))
    } else {
      tableItems.append(.field("Length", "Unknown"))
    }

    tableView.reloadData()
  }
}

extension StarshipDetailViewController {
  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    tableItems.count
  }

  override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    starship?.name
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let item = tableItems[indexPath.row]

    switch item {
    case .image(let image):
      guard let cell = tableView.dequeueReusableCell(
        withIdentifier: "ImageCell", for: indexPath) as? StarshipImageCell else {
        return UITableViewCell()
      }
      cell.starshipImageView.image = image
      return cell

    case let .field(title, subtitle):
      guard let cell = tableView.dequeueReusableCell(
        withIdentifier: "FieldCell", for: indexPath) as? StarshipFieldCell else {
        return UITableViewCell()
      }
      cell.textLabel?.text = title
      cell.detailTextLabel?.text = subtitle
      cell.textLabel?.textColor = .starwarsStarshipGrey
      cell.detailTextLabel?.textColor = .starwarsYellow
      cell.backgroundColor = .clear
      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
    }
  }
}
10. Starship.swift
import Foundation
import UIKit

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
}

extension Starship {
  var image: UIImage? {
    let imageName = name.lowercased().replacingOccurrences(of: " ", with: "_")
    return UIImage(named: imageName)
  }
}

// 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
extension Starship {
  static var all: [Starship] {
    guard let url = Bundle.main.url(forResource: "Starships", withExtension: "json") else {
      return []
    }
    do {
      let data = try Data(contentsOf: url)
      let response = try JSONDecoder().decode(Response.self, from: data)
      return response.allStarships.compactMap { $0["node"] }
    } catch {
      print("Could not decode starship data from JSON")
      print(error)
      return []
    }
  }
}

private extension Starship {
  struct Response: Decodable {
    let allStarships: [[String: Starship]]
  }
}
11. StarshipDetailTableItem.swift
import Foundation
import UIKit

enum StarshipDetailTableItem {
  case image(UIImage)
  case field(String, String)
}
12. UIColor+Extensions.swift
import UIKit

extension UIColor {
  static let starwarsYellow = UIColor(red: 250 / 255, green: 202 / 255, blue: 56 / 255, alpha: 1.0)
  static let starwarsSpaceBlue = UIColor(red: 5 / 255, green: 10 / 255, blue: 85 / 255, alpha: 1.0)
  static let starwarsStarshipGrey = UIColor(red: 159 / 255, green: 150 / 255, blue: 135 / 255, alpha: 1.0)
}
13. CGContext+Extensions.swift
import CoreGraphics

extension CGContext {
  func drawLinearGradient(
    in rect: CGRect,
    startingWith startColor: CGColor,
    finishingWith endColor: CGColor
  ) {
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let locations: [CGFloat] = [0.0, 1.0]
    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()
  }
}

後記

本篇主要講述了關於線、矩形和漸變的繪製,感興趣的給個贊或者關注~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章