美文网首页
CoreGraphic框架解析 (二十三) —— Gradien

CoreGraphic框架解析 (二十三) —— Gradien

作者: 刀客传奇 | 来源:发表于2020-07-29 18:12 被阅读0次

    版本记录

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

    相关文章

      网友评论

          本文标题:CoreGraphic框架解析 (二十三) —— Gradien

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