CGPatternCallback在iOS 12中崩溃

时间:2018-09-13 15:29:53

标签: ios swift core-graphics ios12

以下类实现带有条纹图案背景的视图。它在iOS 11中可以正常工作,但是在回调方法中调用load(as:)时,在iOS 12中使用EXC_BAD_ACCESS崩溃。

欢迎任何指向我做错事情的指针。

import UIKit

class LinedView: UIView {
  var colors: [UIColor] = [] {
    didSet {
      setNeedsDisplay()
    }
  }

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

    var patternCallback = CGPatternCallbacks(
      version: 0,
      drawPattern: {pointer, context in
        guard let colors = pointer?.load(as: [UIColor].self) else { return }
        for (index, color) in colors.enumerated() {
          context.setFillColor(color.cgColor)
          context.fill(CGRect(x: CGFloat(index) * 2 + CGFloat(index - 1) + 1, y: 0, width: 2, height: 1))
        }

    },
      releaseInfo: nil
    )

    let width = CGFloat(colors.count * 3)
    withUnsafeMutablePointer(to: &colors) {
      guard let pattern = CGPattern(
        info: $0,
        bounds: .init(x: 0, y: 0, width: width, height: 1),
        matrix: .identity,
        xStep: width + 1,
        yStep: 1,
        tiling: .constantSpacingMinimalDistortion,
        isColored: true,
        callbacks: &patternCallback
        ) else { return }

      if let patternSpace = CGColorSpace(patternBaseSpace: nil) {
        context.setFillColorSpace(patternSpace)
        var alpha: CGFloat = 1
        context.setFillPattern(pattern, colorComponents: &alpha)
        context.fill(rect)
      }
    }
  }
}

0 个答案:

没有答案