CoreGraphic框架解析 (二十一) —— Curves and Layers(二)

版本記錄

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

前言

quartz是一個通用的術語,用于描述在iOSMAC OS X 中整個媒體層用到的多種技術 包括圖形、動畫、音頻、適配。Quart 2D 是一組二維繪圖和渲染API,Core Graphic會使用到這組API,Quartz 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(一)

源碼

1. Swift

首先看下代碼組織結構

下面就是源碼了

1. AppDelegate.swift
import UIKit
import TwitterKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    TWTRTwitter.sharedInstance().start(withConsumerKey:"HO7JmJZdqvElOo3ERJR4FQ", consumerSecret:"hheWs2LgY9hJGecKxX074tUJ9hOUkyonm3UKbcXRjE4")
    return true
  }

  func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    return TWTRTwitter.sharedInstance().application(app, open: url, options: options)
  }
}
2. ContainerScrollView.swift
import UIKit

class ContainerScrollView: UIScrollView {
  var scrollView: UIScrollView?

  func setScrollView(_ scrollView: UIScrollView) {
    self.scrollView = scrollView
    addSubview(scrollView)
  }
}
3. RageLevel.swift
import UIKit

enum RageLevel: Int, CaseIterable {
  case happy, somewhatHappy, neutral, somewhatAngry, angry

  var image: UIImage {
    switch self {
    case .happy: return UIImage(named: "happy")!
    case .somewhatHappy: return UIImage(named: "somewhat_happy")!
    case .neutral: return UIImage(named: "neutral")!
    case .somewhatAngry: return UIImage(named: "somewhat_angry")!
    case .angry: return UIImage(named: "angry")!
    }
  }

  var tweet: String {
    switch self {
    case .happy: return "The world is my oyster - raw, wriggling, and danglng from my mouth."
    case .somewhatHappy: return "Get down with your bad self!"
    case .neutral: return "Hmm ... Not good, not bad.  Not happy.  Not sad."
    case .somewhatAngry: return "Core breach imminent - stand back before I go thermonuclear"
    case .angry: return "FFFFFFFUUUUUUUUU!!!!1!!!"
    }
  }
}
4. SkyView.swift
import UIKit

class SkyView: UIView {
  private var rageLevel: RageLevel = .happy

  func setRageLevel(_ rageLevel: RageLevel) {
    self.rageLevel = rageLevel
    setNeedsDisplay()
  }

  private func degreesToRadians(_ degrees: CGFloat) -> CGFloat {
    return CGFloat.pi * degrees/180.0
  }

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

    let colorSpace = CGColorSpaceCreateDeviceRGB()

    drawSky(in: rect, rageLevel: rageLevel, context: context, colorSpace: colorSpace)
    drawMountains(in: rect, in: context, with: colorSpace)
    drawGrass(in: rect, in: context, with: colorSpace)
    drawFlowers(in: rect, in: context, with: colorSpace)
  }

  private func drawSky(in rect: CGRect, rageLevel: RageLevel, context: CGContext, colorSpace: CGColorSpace) {
    let baseColor: UIColor
    let middleStop: UIColor
    let farStop: UIColor

    switch rageLevel {
    case .happy:
      baseColor = UIColor(red: 0 / 255.0, green: 158.0 / 255.0, blue: 183.0 / 255.0, alpha: 1.0)
      middleStop = UIColor(red: 0.0 / 255.0, green: 255.0 / 255.0, blue: 252.0 / 255.0, alpha: 1.0)
      farStop = UIColor(red: 255.0 / 255.0, green: 255.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0)
    case .somewhatHappy:
      baseColor = UIColor(red: 0 / 255.0, green: 158.0 / 255.0, blue: 183.0 / 255.0, alpha: 1.0)
      middleStop = UIColor(red: 144.0 / 255.0, green: 152.0 / 255.0, blue: 253.0 / 255.0, alpha: 1.0)
      farStop = UIColor(red: 96.0 / 255.0, green: 111.0 / 255.0, blue: 144.0 / 255.0, alpha: 1.0)
    case .neutral:
      baseColor = UIColor(red: 148.0 / 255.0, green: 158.0 / 255.0, blue: 183.0 / 255.0, alpha: 1.0)
      middleStop = UIColor(red: 127.0 / 255.0, green: 138.0 / 255.0, blue: 166.0 / 255.0, alpha: 1.0)
      farStop = UIColor(red: 96.0 / 255.0, green: 111.0 / 255.0, blue: 144.0 / 255.0, alpha: 1.0)
    case .somewhatAngry:
      baseColor = UIColor(red: 255.0 / 255.0, green: 147.0 / 255.0, blue: 167.0 / 255.0, alpha: 1.0)
      middleStop = UIColor(red: 127.0 / 255.0, green: 138.0 / 255.0, blue: 166.0 / 255.0, alpha: 1.0)
      farStop = UIColor(red: 107.0 / 255.0, green: 107.0 / 255.0, blue: 107.0 / 255.0, alpha: 1.0)
    case .angry:
      baseColor = UIColor(red: 255.0 / 255.0, green: 0 / 255.0, blue: 0 / 255.0, alpha: 1.0)
      middleStop = UIColor(red: 140.0 / 255.0, green: 33.0 / 255.0, blue: 33.0 / 255.0, alpha: 1.0)
      farStop = UIColor(red: 0 / 255.0, green: 0 / 255.0, blue: 0 / 255.0, alpha: 1.0)
    }

    context.saveGState()
    defer { context.restoreGState() }

    let gradientColors = [baseColor.cgColor, middleStop.cgColor, farStop.cgColor]
    let locations: [CGFloat] = [0.0, 0.1, 0.25]

    let startPoint = CGPoint(x: rect.size.height/2, y: 0)
    let endPoint = CGPoint(x: rect.size.height/2, y: rect.size.width)

    if let gradient = CGGradient.init(colorsSpace: colorSpace, colors: gradientColors as CFArray, locations: locations) {
      context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: [])
    }
  }

  private func drawMountains(in rect: CGRect, in context: CGContext, with colorSpace: CGColorSpace?) {
    let darkColor = UIColor(red: 1.0 / 255.0, green: 93.0 / 255.0, blue: 67.0 / 255.0, alpha: 1)
    let lightColor = UIColor(red: 63.0 / 255.0, green: 109.0 / 255.0, blue: 79.0 / 255.0, alpha: 1)
    let rectWidth = rect.size.width

    let mountainColors = [darkColor.cgColor, lightColor.cgColor]
    let mountainLocations: [CGFloat] = [0.1, 0.2]
    guard let mountainGrad = CGGradient.init(colorsSpace: colorSpace, colors: mountainColors as CFArray, locations: mountainLocations) else {
      return
    }

    let mountainStart = CGPoint(x: rect.size.height / 2, y: 100)
    let mountainEnd = CGPoint(x: rect.size.height / 2, y: rect.size.width)

    context.saveGState()
    defer { context.restoreGState() }

    let backgroundMountains = CGMutablePath()
    backgroundMountains.move(to: CGPoint(x: -5, y: 157), transform: .identity)
    backgroundMountains.addQuadCurve(to: CGPoint(x: 77, y: 157), control: CGPoint(x: 30, y: 129), transform: .identity)
    backgroundMountains.addCurve(to: CGPoint(x: 303, y: 125), control1: CGPoint(x: 190, y: 210), control2: CGPoint(x: 200, y: 70), transform: .identity)
    backgroundMountains.addQuadCurve(to: CGPoint(x: 350, y: 150), control: CGPoint(x: 340, y: 150), transform: .identity)
    backgroundMountains.addQuadCurve(to: CGPoint(x: 410, y: 145), control: CGPoint(x: 380, y: 155), transform: .identity)
    backgroundMountains.addCurve(to: CGPoint(x: rectWidth, y: 165), control1: CGPoint(x: rectWidth - 90, y: 100), control2: CGPoint(x: rectWidth - 50, y: 190), transform: .identity)
    backgroundMountains.addLine(to: CGPoint(x: rectWidth - 10, y: rect.size.width), transform: .identity)
    backgroundMountains.addLine(to: CGPoint(x: -5, y: rect.size.width), transform: .identity)
    backgroundMountains.closeSubpath()

    // Background Mountain Drawing
    context.addPath(backgroundMountains)

    context.clip()
    context.drawLinearGradient(mountainGrad, start: mountainStart, end: mountainEnd, options: [])
    context.setLineWidth(4)

    // Background Mountain Stroking
    context.addPath(backgroundMountains)
    context.setStrokeColor(UIColor.black.cgColor)
    context.strokePath()

    // Foreground Mountains
    let foregroundMountains = CGMutablePath()
    foregroundMountains.move(to: CGPoint(x: -5, y: 190), transform: .identity)
    foregroundMountains.addCurve(to: CGPoint(x: 303, y: 190), control1: CGPoint(x: 160, y: 250), control2: CGPoint(x: 200, y: 140), transform: .identity)
    foregroundMountains.addCurve(to: CGPoint(x: rectWidth, y: 210), control1: CGPoint(x: rectWidth - 150, y: 250), control2: CGPoint(x: rectWidth - 50, y: 170), transform: .identity)
    foregroundMountains.addLine(to: CGPoint(x: rectWidth, y: 230), transform: .identity)
    foregroundMountains.addCurve(to: CGPoint(x: -5, y: 225), control1: CGPoint(x: 300, y: 260), control2: CGPoint(x: 140, y: 215), transform: .identity)
    foregroundMountains.closeSubpath()

    // Foreground Mountain drawing
    context.addPath(foregroundMountains)
    context.clip()
    context.setFillColor(darkColor.cgColor)
    context.fill(CGRect(x: 0, y: 170, width: rectWidth, height: 90))

    // Foreground Mountain stroking
    context.addPath(foregroundMountains)
    context.setStrokeColor(UIColor.black.cgColor)
    context.strokePath()
  }

  private func drawGrass(in rect: CGRect, in context: CGContext, with colorSpace: CGColorSpace?) {
    context.saveGState()
    defer { context.restoreGState() }

    let grassStart = CGPoint(x: rect.size.height / 2, y: 100)
    let grassEnd = CGPoint(x: rect.size.height / 2, y: rect.size.width)
    let rectWidth = rect.size.width

    let grass = CGMutablePath()
    grass.move(to: CGPoint(x: rectWidth, y: 230), transform: .identity)
    grass.addCurve(to: CGPoint(x: 0, y: 225), control1: CGPoint(x: 300, y: 260), control2: CGPoint(x: 140, y: 215), transform: .identity)
    grass.addLine(to: CGPoint(x: 0, y: rect.size.width), transform: .identity)
    grass.addLine(to: CGPoint(x: rectWidth, y: rect.size.width), transform: .identity)

    context.addPath(grass)
    context.clip()

    let lightGreen = UIColor(red: 39.0 / 255.0, green: 171.0 / 255.0, blue: 95.0 / 255.0, alpha: 1)
    let darkGreen = UIColor(red: 0.0 / 255.0, green: 134.0 / 255.0, blue: 61.0 / 255.0, alpha: 1)

    let grassColors = [lightGreen.cgColor, darkGreen.cgColor]
    let grassLocations: [CGFloat] = [0.3, 0.4]
    if let grassGrad = CGGradient.init(colorsSpace: colorSpace, colors: grassColors as CFArray, locations: grassLocations) {
      context.drawLinearGradient(grassGrad, start: grassStart, end: grassEnd, options: [])
    }

    context.setLineWidth(1)
    context.setFillColor(UIColor.white.cgColor)
    context.setStrokeColor(UIColor.black.cgColor)
  }

  private func drawPetal(in rect: CGRect, inDegrees degrees: Int, inContext context: CGContext) {
    context.saveGState()
    defer { context.restoreGState() }

    let flowerPetal = CGMutablePath()

    let midX = rect.midX
    let midY = rect.midY

    let transform = CGAffineTransform(translationX: -midX, y: -midY).concatenating(CGAffineTransform(rotationAngle:
      degreesToRadians(CGFloat(degrees)))).concatenating(CGAffineTransform(translationX: midX, y: midY))

    flowerPetal.addEllipse(in: rect, transform: transform)
    context.addPath(flowerPetal)
    context.setStrokeColor(UIColor.black.cgColor)
    context.strokePath()
    context.setFillColor(UIColor.white.cgColor)
    context.addPath(flowerPetal)
    context.fillPath()
  }

  private func drawFlowers(in rect: CGRect, in context: CGContext, with colorSpace: CGColorSpace?) {
    context.saveGState()
    defer { context.restoreGState() }

    let flowerSize = CGSize(width: 300, height: 300)
    guard let flowerLayer = CGLayer(context, size: flowerSize, auxiliaryInfo: nil) else {
      return
    }

    guard let flowerContext = flowerLayer.context else {
      return
    }

    // Draw petals of the flower
    drawPetal(in: CGRect(x: 125, y: 230, width: 9, height: 14), inDegrees: 0, inContext: flowerContext)
    drawPetal(in: CGRect(x: 115, y: 236, width: 10, height: 12), inDegrees: 300, inContext: flowerContext)
    drawPetal(in: CGRect(x: 120, y: 246, width: 9, height: 14), inDegrees: 5, inContext: flowerContext)
    drawPetal(in: CGRect(x: 128, y: 246, width: 9, height: 14), inDegrees: 350, inContext: flowerContext)
    drawPetal(in: CGRect(x: 133, y: 236, width: 11, height: 14), inDegrees: 80, inContext: flowerContext)

    let center = CGMutablePath()
    let ellipse = CGRect(x: 126, y: 242, width: 6, height: 6)
    center.addEllipse(in: ellipse, transform: .identity)

    let orangeColor = UIColor(red: 255 / 255.0, green: 174 / 255.0, blue: 49.0 / 255.0, alpha: 1.0)

    // Draw flower
    flowerContext.addPath(center)
    flowerContext.setStrokeColor(UIColor.black.cgColor)
    flowerContext.strokePath()
    flowerContext.setFillColor(orangeColor.cgColor)
    flowerContext.addPath(center)
    flowerContext.fillPath()
    flowerContext.move(to: CGPoint(x: 135, y: 249))
    context.setStrokeColor(UIColor.black.cgColor)
    flowerContext.addQuadCurve(to: CGPoint(x: 133, y: 270), control: CGPoint(x: 145, y: 250))
    flowerContext.strokePath()

    // Draw clones
    context.draw(flowerLayer, at: CGPoint(x: 0, y: 0))
    context.translateBy(x: 20, y: 10)
    context.draw(flowerLayer, at: CGPoint(x: 0, y: 0))
    context.translateBy(x: -30, y: 5)
    context.draw(flowerLayer, at: CGPoint(x: 0, y: 0))
    context.translateBy(x: -20, y: -10)
    context.draw(flowerLayer, at: CGPoint(x: 0, y: 0))
  }
}
5. ViewController.swift
import UIKit
import TwitterKit

class ViewController: UIViewController, UIScrollViewDelegate {
  @IBOutlet weak var skyView: SkyView!
  @IBOutlet weak var containerScrollView: ContainerScrollView!

  override func viewDidLoad() {
    super.viewDidLoad()
    let viewWidth = view.frame.size.width
    let scrollView = UIScrollView(frame: CGRect(x: viewWidth/4, y: 0, width: viewWidth/2, height: 300))
    scrollView.contentSize = CGSize(width: viewWidth * 2.5, height: 200)
    scrollView.isPagingEnabled = true
    scrollView.clipsToBounds = false
    scrollView.delegate = self;

    let scrollViewWidth = scrollView.frame.size.width

    for rageLevel in RageLevel.allCases {
      let imageView = UIImageView.init(image: rageLevel.image)
      let currentXOffset = (scrollViewWidth/2 - imageView.frame.size.width/2) + CGFloat(rageLevel.rawValue) * scrollViewWidth
      let button = UIButton(frame: CGRect(x: currentXOffset, y: 0, width: imageView.frame.size.width, height: imageView.frame.size.height))
      button.tag = rageLevel.rawValue
      button.setImage(rageLevel.image, for: .normal)
      button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
      scrollView.addSubview(button)
    }

    containerScrollView.setScrollView(scrollView)
  }

  func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    let pageNum = Int(scrollView.contentOffset.x / scrollView.frame.size.width)
    if let rageLevel = RageLevel(rawValue: pageNum) {
      skyView.setRageLevel(rageLevel)
    }
  }

  @objc func buttonTapped(sender: UIButton) {
    if (TWTRTwitter.sharedInstance().sessionStore.hasLoggedInUsers()) {
      showTweetCompose(sender.tag)
    } else {
      TWTRTwitter.sharedInstance().logIn { [weak self] session, error in
        guard let self = self else { return }

        if session != nil {
          self.showTweetCompose(sender.tag)
        } else {
          let alert = UIAlertController(title: "Twitter Unavailable", message: "Please turn to your nearest mirror and rage away", preferredStyle: .alert)
          alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil))
          self.present(alert, animated: false, completion: nil)
        }
      }
    }
  }

  private func showTweetCompose(_ index: Int) {
    let composer = TWTRComposer()

    if let rageLevel = RageLevel(rawValue: index) {
      composer.setText(rageLevel.tweet)
      composer.setImage(rageLevel.image)
    }

    composer.show(from: self, completion: nil)
  }
}

下面看下實際效果

后記

本篇主要講述了Curves and Layers,感興趣的給個贊或者關注~~~

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容