【问题标题】:Custom gradient BackgroundView for iOS not workingiOS的自定义渐变BackgroundView不起作用
【发布时间】:2011-06-28 16:22:59
【问题描述】:

我有以下 UIView 自定义类:

@implementation BackgroundView

- (void)drawRect:(CGRect)rect 
{

    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGGradientRef glossGradient;
    CGColorSpaceRef rgbColorspace;
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };

    float r = (255.0)/(255.0);
    float g = (165.0)/(255.0);
    float b = (0.0)/(255.0);

    float rr = (238.0)/(255.0);
    float gg = (118.0)/(255.0);
    float bb = (0.0)/(255.0);

    CGFloat components[8] = { r, g, b, 1.0,  // Start color
        rr, gg, bb, 1.0 }; // End color

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

    CGRect currentBounds = self.bounds;
    CGPoint topCenter = CGPointMake(CGRectGetMidX(currentBounds), 0.0f);
    CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds));
    CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, 0);

    CGGradientRelease(glossGradient);
    CGColorSpaceRelease(rgbColorspace); 
}


@end

基本上,它应该制作橙色渐变。值“r”、“g”和“b”用于浅橙色,值“rr”、“gg”、“bb”用于深橙色。但它不起作用。只有框架的顶部是橙色的,框架的底部是黑色的。我似乎无法摆脱黑色。

我会为橙色漂亮的渐变使用什么值。有人可以找出错误吗?我找不到任何东西。非常感谢!

【问题讨论】:

    标签: iphone ios uiview gradient


    【解决方案1】:

    那是因为您指定渐变的终点位于 currentBounds 的中间 - 请参阅此行:

    CGPoint midCenter = CGPointMake(CGRectGetMidX(currentBounds), CGRectGetMidY(currentBounds));
    

    要消除黑色,请确保 y 坐标位于视图的底部。

    或者,您可以使用此代码在终点之后扩展渐变

     CGContextDrawLinearGradient(currentContext, glossGradient, topCenter, midCenter, kCGGradientDrawsAfterEndLocation);
    

    【讨论】:

      猜你喜欢
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2017-08-19
      • 2012-10-17
      相关资源
      最近更新 更多