0

我正在尝试调试一个真正困扰我的问题。基本上,我有一个 UIView 子类,它根据我在 init 方法中提供的颜色在 drawRect: 中为自身绘制渐变。当视图再次绘制自身时会出现问题。如果我在视图上调用 setNeedsDisplay,或者说视图由于内存不足警告而被删除,并且稍后会重新添加(这也会再次触发 drawRect:),那么视图的背景是完全空白的。我不确定为什么重绘渐变会导致这种情况发生;有人知道可能出了什么问题吗?这是我在drawRect中的代码摘录:

CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(currentContext);
int startcolorNumComponents = CGColorGetNumberOfComponents(self.topColor.CGColor);
int endcolorNumComponents = CGColorGetNumberOfComponents(self.bottomColor.CGColor);

// get the array of floats for each of the gradient colors
const CGFloat *startComponents = CGColorGetComponents(self.topColor.CGColor);
const CGFloat *endComponents = CGColorGetComponents(self.bottomColor.CGColor);

CGFloat redStart = startComponents[0];
CGFloat greenStart = (startcolorNumComponents != 2 )? startComponents[1] : startComponents[0];
CGFloat blueStart = (startcolorNumComponents != 2 )? startComponents[2] : startComponents[0];
CGFloat startAlpha = (startcolorNumComponents != 2 )? startComponents[3] : startComponents[1];

CGFloat redEnd = endComponents[0];
CGFloat greenEnd = (endcolorNumComponents != 2) ? endComponents[1] : endComponents[0];
CGFloat blueEnd = (endcolorNumComponents != 2) ? endComponents[2] : endComponents[0];
CGFloat endAlpha = (endcolorNumComponents != 2) ? endComponents[3] : endComponents[1];

CGFloat components[8] = { redStart, greenStart, blueStart, startAlpha, redEnd, greenEnd, blueEnd, endAlpha };

size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };

CGGradientRef glossGradient = CGGradientCreateWithColorComponents(CGColorSpaceCreateDeviceRGB(), components, locations, num_locations);

CGPoint gradientStart = CGPointMake(CGRectGetMidX(self.bounds), self.bounds.origin.x);
CGPoint gradientEnd = CGPointMake(CGRectGetMidX(self.bounds),self.bounds.size.height));

CGContextDrawLinearGradient(currentContext, glossGradient, gradientStart, gradientEnd, 0.0);
CGGradientRelease(glossGradient);
CGContextRestoreGState(currentContext);
4

1 回答 1

0

我认为这是一个内存问题。修复内存泄漏后,这不再发生在我身上。

于 2010-07-06T22:33:54.140 回答