【发布时间】:2019-03-01 15:48:30
【问题描述】:
我遇到了内存问题:
使用自定义 Background.m 类,我正在根据传递给该类的颜色选择创建渐变背景。问题出现在似乎有泄漏,没有什么令人兴奋的,但随着时间的推移而积累。在 drawRect 中释放上下文消除了内存问题,但是没有绘制渐变。最好的解决方案/解决方法是什么?使用 Apple 的渐变?下面是传递给 Background 类的 drawRect 方法的代码:
//1. create vars
float increment = 1.0f / (colours.count-1);
CGFloat * locations = (CGFloat *)malloc((int)colours.count*sizeof(CGFloat));
CFMutableArrayRef mref = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
//2. go through the colours, creating cgColors and locations
for (int n = 0; n < colours.count; n++){
CFArrayAppendValue(mref, (id)[colours[n] CGColor]);
locations[n]=(n*increment);
}
//3. create gradient
CGContextRef ref = UIGraphicsGetCurrentContext();
CGColorSpaceRef spaceRef = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradientRef = CGGradientCreateWithColors(spaceRef, mref, locations);
if (isHorizontal){
CGContextDrawLinearGradient(ref, gradientRef, CGPointMake(0.0, 0.0), CGPointMake(self.frame.size.width, 0.0), kCGGradientDrawsAfterEndLocation);
} else if (isDiagonal) {
CGContextDrawLinearGradient(ref, gradientRef, CGPointMake(0.0, 0.0), CGPointMake(self.frame.size.width, self.frame.size.height), kCGGradientDrawsAfterEndLocation);
} else {
CGContextDrawLinearGradient(ref, gradientRef, CGPointMake(0.0, 0.0), CGPointMake(0.0, self.frame.size.height), kCGGradientDrawsAfterEndLocation);
}
CGContextRelease(ref); //ISSUE
CGColorSpaceRelease(spaceRef);
CGGradientRelease(gradientRef);
【问题讨论】:
-
您不拥有 ref。你借了一个