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

版本记录

版本号 时间
V1.0 2020.07.29 星期三

前言

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

首先看下代码组织结构

接着,看下sb中的内容

下面就是源码了

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的简单示例,感兴趣的给个赞或者关注~~~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266