美文网首页傲视苍穹iOS《Swift》VIP专题
CoreGraphic框架解析 (十五)—— Arcs 和 Pa

CoreGraphic框架解析 (十五)—— Arcs 和 Pa

作者: 刀客传奇 | 来源:发表于2019-02-11 21:12 被阅读12次

    版本记录

    版本号 时间
    V1.0 2019.02.11 星期一

    前言

    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 (一)

    源码

    1. Swift

    首先看下工程组织结构

    1. TutorialsViewController.swift
    
    import UIKit
    
    class TutorialsViewController: UIViewController {
      @IBOutlet var tableView: UITableView!
      
      let viewModel = TutorialsViewModel()
      
      override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "Learning Agenda" 
        
        tableView.delegate = self
        tableView.dataSource = self
      }
    }
    
    extension TutorialsViewController: UITableViewDataSource {
      func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.numberOfSections
      }
      
      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRows(in: section)
      }
      
      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CoolCell", for: indexPath)
        
        if cell.backgroundView?.isKind(of: CustomCellBackground.self) != true {
          cell.backgroundView = CustomCellBackground()
        }
        
        if cell.selectedBackgroundView?.isKind(of: CustomCellBackground.self) != true {
          cell.selectedBackgroundView = CustomCellBackground()
        }
        
        cell.textLabel?.text = viewModel.text(at: indexPath)
        
        return cell
      }
    }
    
    extension TutorialsViewController: UITableViewDelegate {
      func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
      }
      
      func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        guard let customHeaderView = CustomHeader.loadViewFromNib() else {
          return nil
        }
        
        customHeaderView.titleLabel.text = self.tableView(tableView, titleForHeaderInSection: section)
        
        if TutorialsViewModel.Section(rawValue: section) == .thingsLearned {
          customHeaderView.startColor = UIColor.rwLightPurple
          customHeaderView.endColor = UIColor.rwDarkPurple
        }
        
        return customHeaderView
      }
      
      func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return viewModel.title(for: section)
      }
      
      func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 30
      }
      
      func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return CustomFooter()
      }
    }
    
    2. CustomCellBackground.swift
    
    import UIKit
    
    class CustomCellBackground: UIView {
      override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()!
        
        context.drawLinearGradient(rect: bounds, startColor: .white, endColor: .rwLightGray)
      }  
    }
    
    3. CustomHeader.swift
    
    import UIKit
    
    class CustomHeader: UIView {
      @IBOutlet public var titleLabel: UILabel!
      
      var startColor = UIColor.rwLightBlue
      var endColor = UIColor.rwDarkBlue
      var coloredBoxHeight: CGFloat = 40
      
      override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()!
        
        var coloredBoxRect = bounds
        coloredBoxRect.size.height = coloredBoxHeight
        
        var paperRect = bounds
        paperRect.origin.y += coloredBoxHeight
        paperRect.size.height = bounds.height - coloredBoxHeight
        
        context.saveGState()
        context.setShadow(offset: CGSize(width: 0, height: 2), blur: 3.0, color: UIColor.rwShadow.cgColor)
        context.setFillColor(startColor.cgColor)
        context.fill(coloredBoxRect)
        context.restoreGState()
        
        context.drawGlossAndGradient(rect: coloredBoxRect, startColor: startColor, endColor: endColor)
        context.setStrokeColor(endColor.cgColor)
        context.setLineWidth(1)
        context.stroke(coloredBoxRect.rectFor1PxStroke())
      } 
      
      class func loadViewFromNib() -> CustomHeader? {
        let nib = UINib(nibName: "CustomHeader", bundle: nil)
        return nib.instantiate(withOwner: CustomHeader()).first as? CustomHeader
      }
    }
    
    4. Extensions.swift
    
    import UIKit
    
    extension UIColor {
      static let rwShadow = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5)
      static let rwLightGray = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1)
      static let rwDarkGray = UIColor(red: 187/255.0, green: 187/255.0, blue: 187/255.0, alpha: 1)
      static let rwLightBlue = UIColor(red: 105/255.0, green: 179/255.0, blue: 216/255.0, alpha: 1)
      static let rwDarkBlue = UIColor(red: 21/255.0, green: 92/255.0, blue: 136/255.0, alpha: 1)
      static let rwLightPurple = UIColor(red: 147/255.0, green: 105/255.0, blue: 216/255.0, alpha: 1)
      static let rwDarkPurple = UIColor(red: 72/255.0, green: 22/255.0, blue: 137/255.0, alpha: 1)
    }
    
    extension CGRect {
      func rectFor1PxStroke() -> CGRect {
        return CGRect(x: origin.x + 0.5, y: origin.y + 0.5, width: size.width - 1, height: size.height - 1)
      }
    }
    
    extension CGContext {
      func drawLinearGradient(rect: CGRect, startColor: UIColor, endColor: UIColor) {
        let gradient = CGGradient(colorsSpace: nil, colors: [startColor.cgColor, endColor.cgColor] as CFArray, locations: [0, 1])!
        
        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: [])    
        restoreGState()
      }
      
      func drawGlossAndGradient(rect: CGRect, startColor: UIColor, endColor: UIColor) {
        drawLinearGradient(rect: rect, startColor: startColor, endColor: endColor)
        
        let glossColor1 = UIColor.white.withAlphaComponent(0.35)
        let glossColor2 = UIColor.white.withAlphaComponent(0.1)
        
        var topHalf = rect
        topHalf.size.height /= 2
        
        drawLinearGradient(rect: topHalf, startColor: glossColor1, endColor: glossColor2)
      }
      
      static func createArcPathFromBottom(of rect: CGRect, arcHeight: CGFloat, startAngle: Angle, endAngle: Angle) -> CGPath {
        // 1
        let arcRect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.height, width: rect.width, height: arcHeight)
        
        // 2
        let arcRadius = (arcRect.height / 2) + pow(arcRect.width, 2) / (8 * arcRect.height)
        let arcCenter = CGPoint(x: arcRect.origin.x + arcRect.width / 2, y: arcRect.origin.y + arcRadius)
        let angle = acos(arcRect.width / (2 * arcRadius))
        let startAngle = CGFloat(startAngle.toRadians()) + angle
        let endAngle = CGFloat(endAngle.toRadians()) - angle
        
        let path = CGMutablePath()
        // 3
        path.addArc(center: arcCenter, radius: arcRadius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
        path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
        path.addLine(to: CGPoint(x: rect.minY, y: rect.maxY))
        // 4
        return path.copy()!
      }
    }
    
    typealias Angle = Measurement<UnitAngle>
    
    extension Measurement where UnitType == UnitAngle {
      init(degrees: Double) {
        self.init(value: degrees, unit: .degrees)
      }
      
      func toRadians() -> Double {
        return converted(to: .radians).value
      }
    }
    
    5. CustomFooter.swift
    
    import UIKit
    
    class CustomFooter: UIView {
      override init(frame: CGRect) {
        super.init(frame: frame)
        
        isOpaque = true
        backgroundColor = .clear
      }
      
      required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
      }
      
      override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()!
        
        let footerRect = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.width, height: bounds.height)
        
        var arcRect = footerRect
        arcRect.size.height = 8
        
        context.saveGState()
        let arcPath = CGContext.createArcPathFromBottom(of: arcRect, arcHeight: 4, startAngle: Angle(degrees: 180), endAngle: Angle(degrees: 360))
        context.addPath(arcPath)
        context.clip()
        
        context.drawLinearGradient(rect: footerRect, startColor: .rwLightGray, endColor: .rwDarkGray)
        context.restoreGState()
        
        context.addRect(footerRect)
        context.addPath(arcPath)
        context.clip(using: .evenOdd)
        context.addPath(arcPath)
        context.setShadow(offset: CGSize(width: 0, height: 2), blur: 3, color: UIColor.rwShadow.cgColor)
        context.fillPath()
      }
    }
    
    6. TutorialsViewModel.swift
    
    import Foundation
    
    final class TutorialsViewModel {
      let thingsToLearn = ["Drawing Rects", "Drawing Gradients", "Drawing Arcs"]
      let thingsLearned = ["Table Views", "UIKit", "Swift"]
      
      var numberOfSections: Int {
        return Section.allCases.count
      }
      
      func numberOfRows(in section: Int) -> Int {
        guard let section = Section(rawValue: section) else { return 0 }
    
        switch section {
        case .thingsToLearn:
          return thingsToLearn.count
        case .thingsLearned:
          return thingsLearned.count
        }
      }
      
      func text(at indexPath: IndexPath) -> String {
        guard let section = Section(rawValue: indexPath.section) else { return "" }
    
        switch section {
        case .thingsToLearn:
          return thingsToLearn[indexPath.row]
        case .thingsLearned:
          return thingsLearned[indexPath.row]
        }
      }
      
      func title(for section: Int) -> String {
        return Section(rawValue: section)?.description ?? ""
      }
    }
    
    extension TutorialsViewModel {
      enum Section: Int, CaseIterable {
        case thingsToLearn
        case thingsLearned
      }
    }
    
    extension TutorialsViewModel.Section: CustomStringConvertible {
      var description: String {
        switch self {
        case .thingsToLearn:
          return "Things To Learn"
        case .thingsLearned:
          return "Things Learned"
        }
      }
    }
    

    后记

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

    相关文章

      网友评论

        本文标题:CoreGraphic框架解析 (十五)—— Arcs 和 Pa

        本文链接:https://www.haomeiwen.com/subject/mirceqtx.html