CoreGraphic框架解析 (二十五) —— 基於Core Graphic的重複圖案的繪製(二) 版本記錄 前言 源碼 後記

版本記錄

版本號 時間
V1.0 2021.03.15 星期一

前言

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的簡單示例(一)
23. CoreGraphic框架解析 (二十三) —— Gradients 和 Contexts的簡單示例(二)
24. CoreGraphic框架解析 (二十四) —— 基於Core Graphic的重複圖案的繪製(一)

源碼

1. Swift

首先看下工程組織結構

下面就是源碼了

1. MedalDrawing.playground
import UIKit

let size = CGSize(width: 120, height: 200)

UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
guard let context = UIGraphicsGetCurrentContext() else {
  fatalError("\(#function):\(#line) Failed to get current context.")
}


// Gold colors
let darkGoldColor = UIColor(red: 0.6, green: 0.5, blue: 0.15, alpha: 1.0)
let midGoldColor = UIColor(red: 0.86, green: 0.73, blue: 0.3, alpha: 1.0)
let lightGoldColor = UIColor(red: 1.0, green: 0.98, blue: 0.9, alpha: 1.0)

////  Add shadow
// let shadow = UIColor.black.withAlphaComponent(0.80)
// let shadowOffset = CGSize(width: 2.0, height: 2.0)
// let shadowBlurRadius: CGFloat = 5
//
// context.setShadow(offset: shadowOffset, blur: shadowBlurRadius, color: shadow.cgColor)
//
// context.beginTransparencyLayer(auxiliaryInfo: nil)

// Lower ribbon
let lowerRibbonPath = UIBezierPath()
lowerRibbonPath.move(to: CGPoint(x: 0, y: 0))
lowerRibbonPath.addLine(to: CGPoint(x: 40, y: 0))
lowerRibbonPath.addLine(to: CGPoint(x: 78, y: 70))
lowerRibbonPath.addLine(to: CGPoint(x: 38, y: 70))
lowerRibbonPath.close()
UIColor.red.setFill()
lowerRibbonPath.fill()

// Clasp
let claspPath = UIBezierPath(roundedRect: CGRect(x: 36, y: 62, width: 43, height: 20), cornerRadius: 5)
claspPath.lineWidth = 5
darkGoldColor.setStroke()
claspPath.stroke()

//// Medallion
// let medallionPath = UIBezierPath(ovalIn: CGRect(x: 8, y: 72, width: 100, height: 100))
// context.saveGState()
// medallionPath.addClip()
//
// let colors = [darkGoldColor.cgColor, midGoldColor.cgColor, lightGoldColor.cgColor] as CFArray
// guard let gradient = CGGradient(
//   colorsSpace: CGColorSpaceCreateDeviceRGB(),
//   colors: colors,
//   locations: [0, 0.51, 1]
// ) else {
//   fatalError("Failed to instantiate an instance of \(String(describing: CGGradient.self))")
// }
// context.drawLinearGradient(gradient, start: CGPoint(x: 40, y: 40), end: CGPoint(x: 100, y: 160), options: [])
// context.restoreGState()
//
////  Create a transform
//// Scale it, and translate it right and down
// var transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
// transform = transform.translatedBy(x: 15, y: 30)
// medallionPath.lineWidth = 2.0
//
////  Apply the transform to the path
// medallionPath.apply(transform)
// medallionPath.stroke()
//
////  Upper ribbon
// let upperRibbonPath = UIBezierPath()
// upperRibbonPath.move(to: CGPoint(x: 68, y: 0))
// upperRibbonPath.addLine(to: CGPoint(x: 108, y: 0))
// upperRibbonPath.addLine(to: CGPoint(x: 78, y: 70))
// upperRibbonPath.addLine(to: CGPoint(x: 38, y: 70))
// upperRibbonPath.close()
//
// UIColor.blue.setFill()
// upperRibbonPath.fill()
//
////  Number One
//
////  Must be NSString to be able to use draw(in:)
// let numberOne = "1" as NSString
// let numberOneRect = CGRect(x: 47, y: 100, width: 50, height: 50)
// guard let font = UIFont(name: "Academy Engraved LET", size: 60) else {
//  fatalError("\(#function):\(#line) Failed to instantiate font with name \"Academy Engraved LET\"")
// }
// let numberOneAttributes = [
//  NSAttributedString.Key.font: font,
//  NSAttributedString.Key.foregroundColor: darkGoldColor
// ]
// numberOne.draw(in: numberOneRect, withAttributes: numberOneAttributes)
//
// context.endTransparencyLayer()

// This code must always be at the end of the playground
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
2. AppDelegate.swift
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?
}
3. 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!

  @IBOutlet weak var medalView: MedalView!

  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)
    }
    checkTotal()
    rotateButton(button)
  }

  private func rotateButton(_  button: UIButton) {
    let layer = button.layer
    let rotationAnimation = CAKeyframeAnimation(keyPath: "transform.rotation")
    rotationAnimation.keyTimes = [0, 1]
    rotationAnimation.values = [0, CGFloat.pi]
    rotationAnimation.duration = 0.25
    layer.add(rotationAnimation, forKey: "transform.rotation")
  }

  @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)
    checkTotal()
  }

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

    // 1 - replace last day with today's actual data
    graphView.graphPoints[graphView.graphPoints.count - 1] = counterView.counter
    // 2 - indicate that the graph needs to be redrawn
    graphView.setNeedsDisplay()
    maxLabel.text = "\(graphView.graphPoints.max() ?? 0)"

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

    // 4 - setup date formatter and calendar
    let today = Date()
    let calendar = Calendar.current

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

    // 5 - set up the day name labels with correct day
    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)
      }
    }
  }

  func checkTotal() {
    if counterView.counter >= 8 {
      medalView.showMedal(show: true)
    } else {
      medalView.showMedal(show: false)
    }
  }
}
4. 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()
  }
}
5. 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()
  }
}
6. 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()
  }
}
7. BackgroundView.swift
import UIKit

@IBDesignable
class BackgroundView: UIView {
  // 1
  @IBInspectable var lightColor: UIColor = .orange
  @IBInspectable var darkColor: UIColor = .yellow
  @IBInspectable var patternSize: CGFloat = 200

  override func draw(_ rect: CGRect) {
    // 2
    guard let context = UIGraphicsGetCurrentContext() else {
      fatalError("\(#function):\(#line) Failed to get current context.")
    }

    // 3
    context.setFillColor(darkColor.cgColor)

    // 4
    context.fill(rect)


    let drawSize = CGSize(width: patternSize, height: patternSize)

    UIGraphicsBeginImageContextWithOptions(drawSize, true, 0.0)
    guard let drawingContext = UIGraphicsGetCurrentContext() else {
      fatalError("\(#function):\(#line) Failed to get current context.")
    }

    // Set the fill color for the new context
    darkColor.setFill()
    drawingContext.fill(CGRect(x: 0, y: 0, width: drawSize.width, height: drawSize.height))

    let trianglePath = UIBezierPath()
    // 1
    trianglePath.move(to: CGPoint(x: drawSize.width / 2, y: 0))
    // 2
    trianglePath.addLine(to: CGPoint(x: 0, y: drawSize.height / 2))
    // 3
    trianglePath.addLine(to: CGPoint(x: drawSize.width, y: drawSize.height / 2))

    // 4
    trianglePath.move(to: CGPoint(x: 0, y: drawSize.height / 2))
    // 5
    trianglePath.addLine(to: CGPoint(x: drawSize.width / 2, y: drawSize.height))
    // 6
    trianglePath.addLine(to: CGPoint(x: 0, y: drawSize.height))

    // 7
    trianglePath.move(to: CGPoint(x: drawSize.width, y: drawSize.height / 2))
    // 8
    trianglePath.addLine(to: CGPoint(x: drawSize.width / 2, y: drawSize.height))
    // 9
    trianglePath.addLine(to: CGPoint(x: drawSize.width, y: drawSize.height))

    lightColor.setFill()
    trianglePath.fill()

    guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
      fatalError("\(#function):\(#line) Failed to get an image from current context.")
    }
    UIGraphicsEndImageContext()

    UIColor(patternImage: image).setFill()
    context.fill(rect)
  }
}
8. MedalView.swift
import UIKit

class MedalView: UIImageView {
  lazy var medalImage = self.createMedalImage()

  // swiftlint:disable function_body_length
  func createMedalImage() -> UIImage {
    debugPrint("creating Medal Image")
    let size = CGSize(width: 120, height: 200)

    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
    guard let context = UIGraphicsGetCurrentContext() else {
      fatalError("\(#function):\(#line) Failed to get current context.")
    }

    // Gold colors
    let darkGoldColor = UIColor(red: 0.6, green: 0.5, blue: 0.15, alpha: 1.0)
    let midGoldColor = UIColor(red: 0.86, green: 0.73, blue: 0.3, alpha: 1.0)
    let lightGoldColor = UIColor(red: 1.0, green: 0.98, blue: 0.9, alpha: 1.0)

    // Add shadow
    let shadow = UIColor.black.withAlphaComponent(0.80)
    let shadowOffset = CGSize(width: 2.0, height: 2.0)
    let shadowBlurRadius: CGFloat = 5

    context.setShadow(offset: shadowOffset, blur: shadowBlurRadius, color: shadow.cgColor)

    context.beginTransparencyLayer(auxiliaryInfo: nil)

    // Lower ribbon
    let lowerRibbonPath = UIBezierPath()
    lowerRibbonPath.move(to: CGPoint(x: 0, y: 0))
    lowerRibbonPath.addLine(to: CGPoint(x: 40, y: 0))
    lowerRibbonPath.addLine(to: CGPoint(x: 78, y: 70))
    lowerRibbonPath.addLine(to: CGPoint(x: 38, y: 70))
    lowerRibbonPath.close()
    UIColor.red.setFill()
    lowerRibbonPath.fill()

    // Clasp
    let claspPath = UIBezierPath(roundedRect: CGRect(x: 36, y: 62, width: 43, height: 20), cornerRadius: 5)
    claspPath.lineWidth = 5
    darkGoldColor.setStroke()
    claspPath.stroke()

    // Medallion
    let medallionPath = UIBezierPath(ovalIn: CGRect(x: 8, y: 72, width: 100, height: 100))
    context.saveGState()
    medallionPath.addClip()

    let colors = [darkGoldColor.cgColor, midGoldColor.cgColor, lightGoldColor.cgColor] as CFArray
    guard let gradient = CGGradient(
      colorsSpace: CGColorSpaceCreateDeviceRGB(),
      colors: colors,
      locations: [0, 0.51, 1]
    ) else {
      fatalError("Failed to instantiate an instance of \(String(describing: CGGradient.self))")
    }
    context.drawLinearGradient(gradient, start: CGPoint(x: 40, y: 40), end: CGPoint(x: 100, y: 160), options: [])
    context.restoreGState()

    // Create a transform
    // Scale it, and translate it right and down
    var transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
    transform = transform.translatedBy(x: 15, y: 30)
    medallionPath.lineWidth = 2.0

    // apply the transform to the path
    medallionPath.apply(transform)
    medallionPath.stroke()

    // Upper ribbon
    let upperRibbonPath = UIBezierPath()
    upperRibbonPath.move(to: CGPoint(x: 68, y: 0))
    upperRibbonPath.addLine(to: CGPoint(x: 108, y: 0))
    upperRibbonPath.addLine(to: CGPoint(x: 78, y: 70))
    upperRibbonPath.addLine(to: CGPoint(x: 38, y: 70))
    upperRibbonPath.close()

    UIColor.blue.setFill()
    upperRibbonPath.fill()

    // Number One

    // Must be NSString to be able to use draw(in:)
    let numberOne = "1" as NSString
    let numberOneRect = CGRect(x: 47, y: 100, width: 50, height: 50)
    guard let font = UIFont(name: "Academy Engraved LET", size: 60) else {
      fatalError("\(#function):\(#line) Failed to instantiate font with name \"Academy Engraved LET\"")
    }
    let numberOneAttributes = [
      NSAttributedString.Key.font: font,
      NSAttributedString.Key.foregroundColor: darkGoldColor
    ]
    numberOne.draw(in: numberOneRect, withAttributes: numberOneAttributes)

    context.endTransparencyLayer()

    // This code must always be at the end of the playground
    guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
      fatalError("\(#function):\(#line) Failed to get an image from current context.")
    }
    UIGraphicsEndImageContext()

    return image
  }

  func showMedal(show: Bool) {
    image = show == true ? medalImage : nil
  }
}

後記

本篇主要講述了基於Core Graphic的重複圖案的繪製,感興趣的給個贊或者關注~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章