版本记录
版本号 | 时间 |
---|---|
V1.0 | 2019.02.12 星期二 |
前言
quartz
是一个通用的术语,用于描述在iOS
和MAC OS X
中整个媒体层用到的多种技术 包括图形、动画、音频、适配。Quart 2D
是一组二维绘图和渲染API
,Core Graphic
会使用到这组API
,Quartz Core
专指Core Animation
用到的动画相关的库、API
和类。CoreGraphics
是UIKit
下的主要绘图系统,频繁的用于绘制自定义视图。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,感兴趣的给个赞或者关注~~~