CGContextDrawLinearGradient calling EXC_BAD_ACCESS

I set up my BEMSimpleLineGraph and was able to do it successfully, except for linear gradient shading. After referencing this code in the above Obj-C project example

CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB(); size_t num_locations = 2; CGFloat locations[2] = { 0.0, 1.0 }; CGFloat components[8] = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0 }; self.myGraph.gradientBottom = CGGradientCreateWithColorComponents(colorspace, components, locations, num_locations); 

and rewriting it in Swift:

 let colorspace:CGColorSpaceRef = CGColorSpaceCreateDeviceRGB() let num_locations:size_t = 2 var locations: [CGFloat] = [0.0, 1.0] var components: [CGFloat] = [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0 ] self.myGraph.gradientBottom = CGGradientCreateWithColorComponents(colorspace, components, locations, num_locations) 

everything builds correctly, but generates an EXC_BAD_ACCESS memory error in the BEMLine.m file, which stops on this line

 CGContextDrawLinearGradient(ctx, self.bottomGradient, CGPointZero, CGPointMake(0, CGRectGetMaxY(fillBottom.bounds)), 0); 

I included the obj-c bridge title, added the CoreGraphics structure, turned on the bottom color in the attributes panel of the corresponding ViewController in the Storyboard, linking to the Apple development pages to ensure the correct data types of all parameters, but I'm still dry. When checking the similarity of errors, I also realized that the same error occurs when trying to draw an upper linear gradient. The error seems to be in Obj-C code trying to draw a gradient, but again I don’t understand what to do.

+5
source share
2 answers

I had the same problem when using BEMSimpleLineGraph from Swift. Fortunately, I found the answer on the Github libraries problem page:

https://github.com/Boris-Em/BEMSimpleLineGraph/issues/105

To solve the problem, I simply declared a global gradient in the Swift class, for example:

 var gradient : CGGradient? 

and just replaced the line

 self.myGraph.gradientBottom = CGGradientCreateWithColorComponents(colorspace, components, locations, num_locations) 

from:

 self.gradient = CGGradientCreateWithColorComponents(colorspace, components, locations, num_locations) self.myGraph.gradientBottom = self.gradient 

Apparently, the gradient otherwise will not remain allocated in memory and at the time the library should use it, it is no longer available.

+5
source

One thing that I note is that you use self.myGraph.gradientBottom in the installation code, and you use self.myGraph.gradientBottom in the drawing code.

Should they be the same? Or did you forget to assign a value to the latter?

0
source

Source: https://habr.com/ru/post/1216416/


All Articles