0
我試圖調試一個真正困擾我的問題。基本上,我有一個UIView子類,它在drawRect中爲自己繪製漸變:基於我在init方法中提供的顏色。問題在視圖重新繪製時發生。如果我在視圖上調用setNeedsDisplay,或者如果說視圖由於內存不足警告而被刪除,並且稍後重新添加(這也會觸發drawRect:),那麼視圖的背景是完全空白的。我不確定爲什麼重繪漸變會導致這種情況發生;有人知道會發生什麼事嗎?下面是我在drawRect中的代碼摘錄:在UIView上繪製漸變在後續調用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);