版本記錄
版本號(hào) | 時(shí)間 |
---|---|
V1.0 | 2019.02.12 星期二 |
前言
quartz
是一個(gè)通用的術(shù)語,用于描述在iOS
和MAC OS X
中整個(gè)媒體層用到的多種技術(shù) 包括圖形、動(dòng)畫、音頻垛吗、適配。Quart 2D
是一組二維繪圖和渲染API
烁登,Core Graphic
會(huì)使用到這組API
怯屉,Quartz Core
專指Core Animation
用到的動(dòng)畫相關(guān)的庫、API
和類饵沧。CoreGraphics
是UIKit
下的主要繪圖系統(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)注~~~