在CALayer中绘制UIBezierPath时的上下文无效

时间:2017-06-23 10:42:48

标签: swift swift3 calayer cgcontext

我试图通过CALayer(CAShapeLayer)子类和覆盖draw(in ctx: CGContext)来实现自定义属性的隐式动画

我想绘制一个UIBezierPath并将其添加到上下文中:

override func draw(in ctx: CGContext) {

    // This causes the error below and nothing is drawn
    let path = UIBezierPath(rect: bounds)
    UIColor.red.setFill()
    path.fill()
    ctx.addPath(path.cgPath)

    // This works just fine!
    // ctx.setFillColor(UIColor.red.cgColor) 
    // ctx.fill(bounds)
}

一旦我尝试使用draw方法中的路径执行任何操作,即使在尝试将其添加到上下文之前,我也会收到此错误。

<Error>: CGContextSetFillColorWithColor: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable. 
<Error>: CGContextSaveGState: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable. 
<Error>: CGContextSetFlatness: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.  
<Error>: CGContextAddPath: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable. 
<Error>: CGContextDrawPath: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.     
<Error>: CGContextRestoreGState: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.

按照建议启用Backtrace会给我这个(只包含一个属性跟踪,它们对于上面错误中的所有值都是相同的):

Jun 23 11:56:11  Project[30178] <Error>: CGContextRestoreGState: invalid context 0x0. Backtrace:
  <_TFC17Project8BarLayer4drawfT2inCSo9CGContext_T_+258>
   <_TToFC17Project8BarLayer4drawfT2inCSo9CGContext_T_+58>
    <CABackingStoreUpdate_+2505>
     <___ZN2CA5Layer8display_Ev_block_invoke+61>
      <_ZN2CA5Layer8display_Ev+1633>
       <_ZN2CA5Layer17display_if_neededEPNS_11TransactionE+315>
        <_ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE+35>
         <_ZN2CA7Context18commit_transactionEPNS_11TransactionE+294>
          <_ZN2CA11Transaction6commitEv+468>
           <_ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv+115>
            <__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__+23>
             <__CFRunLoopDoObservers+391>
              <CFRunLoopRunSpecific+440>
               <-[UIApplication _run]+468>
                <UIApplicationMain+159>
                 <main+55>
                  <start+1>

1 个答案:

答案 0 :(得分:1)

我在输入问题后找到了这个答案:Custom CALayer - invalid context 0x0

问题在于我没有推动上下文:

override func draw(in ctx: CGContext) {

    UIGraphicsPushContext(ctx) // push the context
    let path = UIBezierPath(rect: bounds)
    UIColor.red.setFill()
    path.fill()
    ctx.addPath(path.cgPath)
    UIGraphicsPopContext() // pop it once drawing is complete

   // ctx.setFillColor(UIColor.red.cgColor) This works just fine
   // ctx.fill(bounds)
}