【问题标题】:Drawing gradients on a UIView doesn't work on subsequent calls to drawRect:在 UIView 上绘制渐变不适用于后续对 drawRect 的调用:
【发布时间】:2010-05-04 16:49:24
【问题描述】:

我正在尝试调试一个真正困扰我的问题。基本上,我有一个 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);

【问题讨论】:

    标签: iphone uiview core-graphics gradient


    【解决方案1】:

    我认为这是一个内存问题。修复内存泄漏后,我不再发生这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多