CoreGraphic框架解析 (二十三) —— Gradients 和 Contexts的簡單示例(二)

版本記錄

版本號 時間
V1.0 2020.07.29 星期三

前言

quartz是一個通用的術(shù)語,用于描述在iOSMAC OS X 中整個媒體層用到的多種技術(shù) 包括圖形、動畫、音頻、適配。Quart 2D 是一組二維繪圖和渲染API,Core Graphic會使用到這組API,Quartz Core專指Core Animation用到的動畫相關(guān)的庫、API和類。CoreGraphicsUIKit下的主要繪圖系統(tǒng),頻繁的用于繪制自定義視圖。Core Graphics是高度集成于UIView和其他UIKit部分的。Core Graphics數(shù)據(jù)結(jié)構(gòu)和函數(shù)可以通過前綴CG來識別。在app中很多時候繪圖等操作我們要利用CoreGraphic框架,它能繪制字符串、圖形、漸變色等等,是一個很強(qiáng)大的工具。感興趣的可以看我另外幾篇。
1. CoreGraphic框架解析(一)—— 基本概覽
2. CoreGraphic框架解析(二)—— 基本使用
3. CoreGraphic框架解析(三)—— 類波浪線的實(shí)現(xiàn)
4. CoreGraphic框架解析(四)—— 基本架構(gòu)補(bǔ)充
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的簡單示例(一)

源碼

1. Swift

首先看下代碼組織結(jié)構(gòu)

接著,看下sb中的內(nèi)容

下面就是源碼了

1. ViewController.swift
import UIKit

class ViewController: UIViewController {
  // Counter outlets
  @IBOutlet weak var counterView: CounterView!
  @IBOutlet weak var counterLabel: UILabel!

  @IBOutlet weak var containerView: UIView!
  @IBOutlet weak var graphView: GraphView!

  // Label outlets
  @IBOutlet weak var averageWaterDrunk: UILabel!
  @IBOutlet weak var maxLabel: UILabel!
  @IBOutlet weak var stackView: UIStackView!

  var isGraphViewShowing = false

  @IBAction func pushButtonPressed(_ button: PushButton) {
    if button.isAddButton {
      counterView.counter += 1
    } else {
      if counterView.counter > 0 {
        counterView.counter -= 1
      }
    }
    counterLabel.text = String(counterView.counter)

    if isGraphViewShowing {
      counterViewTap(nil)
    }
  }

  @IBAction func counterViewTap(_ gesture: UITapGestureRecognizer?) {
    if isGraphViewShowing {
      UIView.transition(
        from: graphView,
        to: counterView,
        duration: 1.0,
        options: [.transitionFlipFromLeft, .showHideTransitionViews],
        completion: nil
      )
    } else {
      setupGraphDisplay()
      UIView.transition(
        from: counterView,
        to: graphView,
        duration: 1.0,
        options: [.transitionFlipFromRight, .showHideTransitionViews],
        completion: nil
      )
    }
    isGraphViewShowing.toggle()
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    counterLabel.text = String(counterView.counter)
  }

  func setupGraphDisplay() {
    let maxDayIndex = stackView.arrangedSubviews.count - 1

    graphView.graphPoints[graphView.graphPoints.count - 1] = counterView.counter
    graphView.setNeedsDisplay()
    maxLabel.text = "\(graphView.graphPoints.max() ?? 0)"

    let average = graphView.graphPoints.reduce(0, +) / graphView.graphPoints.count
    averageWaterDrunk.text = "\(average)"

    let today = Date()
    let calendar = Calendar.current

    let formatter = DateFormatter()
    formatter.setLocalizedDateFormatFromTemplate("EEEEE")

    for i in (0...maxDayIndex) {
      if let date = calendar.date(byAdding: .day, value: -i, to: today),
        let label = stackView.arrangedSubviews[maxDayIndex - i] as? UILabel {
        label.text = formatter.string(from: date)
      }
    }
  }
}
2. PushButton.swift
import UIKit

@IBDesignable
class PushButton: UIButton {
  private enum Constants {
    static let plusLineWidth: CGFloat = 3.0
    static let plusButtonScale: CGFloat = 0.6
    static let halfPointShift: CGFloat = 0.5
  }

  private var halfWidth: CGFloat {
    return bounds.width / 2
  }

  private var halfHeight: CGFloat {
    return bounds.height / 2
  }

  @IBInspectable var fillColor: UIColor = .green
  @IBInspectable var isAddButton: Bool = true

  override func draw(_ rect: CGRect) {
    let path = UIBezierPath(ovalIn: rect)
    fillColor.setFill()
    path.fill()

    let plusWidth = min(bounds.width, bounds.height) * Constants.plusButtonScale
    let halfPlusWidth = plusWidth / 2

    let plusPath = UIBezierPath()

    plusPath.lineWidth = Constants.plusLineWidth

    plusPath.move(to: CGPoint(
      x: halfWidth - halfPlusWidth + Constants.halfPointShift,
      y: halfHeight + Constants.halfPointShift))

    plusPath.addLine(to: CGPoint(
      x: halfWidth + halfPlusWidth + Constants.halfPointShift,
      y: halfHeight + Constants.halfPointShift))

    if isAddButton {
      plusPath.move(to: CGPoint(
        x: halfWidth + Constants.halfPointShift,
        y: halfHeight - halfPlusWidth + Constants.halfPointShift))

      plusPath.addLine(to: CGPoint(
        x: halfWidth + Constants.halfPointShift,
        y: halfHeight + halfPlusWidth + Constants.halfPointShift))
    }

    UIColor.white.setStroke()

    plusPath.stroke()
  }
}
3. CounterView.swift
import UIKit

@IBDesignable
class CounterView: UIView {
  private enum Constants {
    static let numberOfGlasses = 8
    static let lineWidth: CGFloat = 5.0
    static let arcWidth: CGFloat = 76

    static var halfOfLineWidth: CGFloat {
      return lineWidth / 2
    }
  }

  @IBInspectable var counter: Int = 5 {
    didSet {
      if counter <= Constants.numberOfGlasses {
        setNeedsDisplay()
      }
    }
  }
  @IBInspectable var outlineColor: UIColor = UIColor.blue
  @IBInspectable var counterColor: UIColor = UIColor.orange

  override func draw(_ rect: CGRect) {
    let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2)

    let radius = max(bounds.width, bounds.height)

    let startAngle: CGFloat = 3 * .pi / 4
    let endAngle: CGFloat = .pi / 4

    let path = UIBezierPath(
      arcCenter: center,
      radius: radius / 2 - Constants.arcWidth / 2,
      startAngle: startAngle,
      endAngle: endAngle,
      clockwise: true)

    path.lineWidth = Constants.arcWidth
    counterColor.setStroke()
    path.stroke()

    let angleDifference: CGFloat = 2 * .pi - startAngle + endAngle
    let arcLengthPerGlass = angleDifference / CGFloat(Constants.numberOfGlasses)
    let outlineEndAngle = arcLengthPerGlass * CGFloat(counter) + startAngle

    let outerArcRadius = bounds.width / 2 - Constants.halfOfLineWidth
    let outlinePath = UIBezierPath(
      arcCenter: center,
      radius: outerArcRadius,
      startAngle: startAngle,
      endAngle: outlineEndAngle,
      clockwise: true)

    let innerArcRadius = bounds.width / 2 - Constants.arcWidth + Constants.halfOfLineWidth
    outlinePath.addArc(
      withCenter: center,
      radius: innerArcRadius,
      startAngle: outlineEndAngle,
      endAngle: startAngle,
      clockwise: false)

    outlinePath.close()

    outlineColor.setStroke()
    outlinePath.lineWidth = Constants.lineWidth
    outlinePath.stroke()

    // Counter View markers
    guard let context = UIGraphicsGetCurrentContext() else {
      return
    }

    context.saveGState()
    outlineColor.setFill()

    let markerWidth: CGFloat = 5.0
    let markerSize: CGFloat = 10.0

    let markerPath = UIBezierPath(rect: CGRect(x: -markerWidth / 2, y: 0, width: markerWidth, height: markerSize))

    context.translateBy(x: rect.width / 2, y: rect.height / 2)

    for i in 1...Constants.numberOfGlasses {
      context.saveGState()
      let angle = arcLengthPerGlass * CGFloat(i) + startAngle - .pi / 2
      context.rotate(by: angle)
      context.translateBy(x: 0, y: rect.height / 2 - markerSize)

      markerPath.fill()
      context.restoreGState()
    }

    context.restoreGState()
  }
}
4. GraphView.swift
import UIKit

@IBDesignable
class GraphView: UIView {
  private enum Constants {
    static let cornerRadiusSize = CGSize(width: 8.0, height: 8.0)
    static let margin: CGFloat = 20.0
    static let topBorder: CGFloat = 60
    static let bottomBorder: CGFloat = 50
    static let colorAlpha: CGFloat = 0.3
    static let circleDiameter: CGFloat = 5.0
  }

  @IBInspectable var startColor: UIColor = .red
  @IBInspectable var endColor: UIColor = .green

  var graphPoints: [Int] = [4, 2, 6, 4, 5, 8, 3]

  // swiftlint:disable:next function_body_length
  override func draw(_ rect: CGRect) {
    let width = rect.width
    let height = rect.height

    let path = UIBezierPath(
      roundedRect: rect,
      byRoundingCorners: UIRectCorner.allCorners,
      cornerRadii: Constants.cornerRadiusSize
    )
    path.addClip()

    guard let context = UIGraphicsGetCurrentContext() else {
      return
    }
    let colors = [startColor.cgColor, endColor.cgColor]

    let colorSpace = CGColorSpaceCreateDeviceRGB()

    let colorLocations: [CGFloat] = [0.0, 1.0]

    guard let gradient = CGGradient(
      colorsSpace: colorSpace,
      colors: colors as CFArray,
      locations: colorLocations
    ) else {
      return
    }

    var startPoint = CGPoint.zero
    var endPoint = CGPoint(x: 0, y: self.bounds.height)
    context.drawLinearGradient(
      gradient,
      start: startPoint,
      end: endPoint,
      options: []
    )

    let margin = Constants.margin
    let columnXPoint = { (column: Int) -> CGFloat in
      let spacing = (width - margin * 2 - 4) / CGFloat((self.graphPoints.count - 1))
      return CGFloat(column) * spacing + margin + 2
    }

    let topBorder: CGFloat = Constants.topBorder
    let bottomBorder: CGFloat = Constants.bottomBorder
    let graphHeight = height - topBorder - bottomBorder
    guard let maxValue = graphPoints.max() else {
      return
    }
    let columnYPoint = { (graphPoint: Int) -> CGFloat in
      let yPoint = CGFloat(graphPoint) / CGFloat(maxValue) * graphHeight
      return graphHeight + topBorder - yPoint
    }

    UIColor.white.setFill()
    UIColor.white.setStroke()

    let graphPath = UIBezierPath()
    graphPath.move(to: CGPoint(x: columnXPoint(0), y: columnYPoint(graphPoints[0])))

    for i in 1..<graphPoints.count {
      let nextPoint = CGPoint(x: columnXPoint(i), y: columnYPoint(graphPoints[i]))
      graphPath.addLine(to: nextPoint)
    }

    context.saveGState()

    guard let clippingPath = graphPath.copy() as? UIBezierPath else {
      return
    }

    clippingPath.addLine(to: CGPoint(x: columnXPoint(graphPoints.count - 1), y: height))
    clippingPath.addLine(to: CGPoint(x: columnXPoint(0), y: height))
    clippingPath.close()

    clippingPath.addClip()

    let highestYPoint = columnYPoint(maxValue)
    startPoint = CGPoint(x: margin, y: highestYPoint)
    endPoint = CGPoint(x: margin, y: self.bounds.height)

    context.drawLinearGradient(
      gradient,
      start: startPoint,
      end: endPoint,
      options: CGGradientDrawingOptions(rawValue: 0)
    )
    context.restoreGState()

    graphPath.lineWidth = 2.0
    graphPath.stroke()

    for i in 0..<graphPoints.count {
      var point = CGPoint(x: columnXPoint(i), y: columnYPoint(graphPoints[i]))
      point.x -= Constants.circleDiameter / 2
      point.y -= Constants.circleDiameter / 2

      let circle = UIBezierPath(
        ovalIn: CGRect(
          origin: point,
          size: CGSize(width: Constants.circleDiameter, height: Constants.circleDiameter)
        )
      )
      circle.fill()
    }

    let linePath = UIBezierPath()

    linePath.move(to: CGPoint(x: margin, y: topBorder))
    linePath.addLine(to: CGPoint(x: width - margin, y: topBorder))

    linePath.move(to: CGPoint(x: margin, y: graphHeight / 2 + topBorder))
    linePath.addLine(to: CGPoint(x: width - margin, y: graphHeight / 2 + topBorder))

    linePath.move(to: CGPoint(x: margin, y: height - bottomBorder))
    linePath.addLine(to: CGPoint(x: width - margin, y: height - bottomBorder))
    let color = UIColor(white: 1.0, alpha: Constants.colorAlpha)
    color.setStroke()

    linePath.lineWidth = 1.0
    linePath.stroke()
  }
}

后記

本篇主要講述了GradientsContexts的簡單示例,感興趣的給個贊或者關(guān)注~~~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容