首页 文章

CGGradientCreateWithColorComponents和alpha channelI

提问于
浏览
3

我正在使用CGGradientCreateWithColorComponents创建 CGGradientRef ,其中记录了支持alpha通道:

此数组中的项目数应为count的乘积和颜色空间中的组件数 . 例如,如果颜色空间是RGBA颜色空间,并且您希望在渐变中使用两种颜色(一种用于起始位置,另一种用于结束位置),则需要在组件中提供8个值 - 红色,绿色,蓝色和第一种颜色的Alpha值,后跟第二种颜色的红色,绿色,蓝色和Alpha值 .

以下是完整的视图实现:

. H

@interface AlphaGrad : UIView

@end

.M

@implementation AlphaGrad

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

-(void) drawRect:(CGRect)rect {

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSaveGState(ctx);
    CGContextClip(ctx);

    CGGradientRef gradient = [self newGradientWithColors:[NSArray arrayWithObjects:[UIColor blackColor], [UIColor colorWithRed:0 green:0 blue:0 alpha:0.0f], nil]
                                               locations:[NSArray arrayWithObjects:@0, @1, nil]];

    CGContextDrawLinearGradient(ctx, gradient, CGPointMake(rect.origin.x, rect.origin.y),
                                CGPointMake(rect.origin.x, rect.origin.y+rect.size.height), kCGGradientDrawsAfterEndLocation);
    CGGradientRelease(gradient);

    CGContextRestoreGState(ctx);
}

- (CGGradientRef)newGradientWithColors:(NSArray*)colorsArray locations:(NSArray*)locationsArray {

  int count = [colorsArray count];

  CGFloat* components = malloc(sizeof(CGFloat)*4*count);
  CGFloat* locations = malloc(sizeof(CGFloat)*count);

  for (int i = 0; i < count; ++i) {
    UIColor* color = [colorsArray objectAtIndex:i];
    NSNumber* location = (NSNumber*)[locationsArray objectAtIndex:i];
    size_t n = CGColorGetNumberOfComponents(color.CGColor);
    const CGFloat* rgba = CGColorGetComponents(color.CGColor);
    if (n == 2) {
      components[i*4] = rgba[0];
      components[i*4+1] = rgba[0];
      components[i*4+2] = rgba[0];
      components[i*4+3] = rgba[1];
    } else if (n == 4) {
      components[i*4] = rgba[0];
      components[i*4+1] = rgba[1];
      components[i*4+2] = rgba[2];
      components[i*4+3] = rgba[3];
    }
    locations[i] = [location floatValue];
  }

  CGContextRef context = UIGraphicsGetCurrentContext();
  CGColorSpaceRef space = CGBitmapContextGetColorSpace(context);
  CGGradientRef gradient = CGGradientCreateWithColorComponents(space, components, locations, count);
  free(components);
  free(locations);
  return gradient;
}
@end

问题是透明度似乎不受支持,透明部分被淹没为白色:
enter image description here

是否可以通过 CGGradientRef 获得透明度以使"lower"子视图部分可见?

1 回答

  • 6

    对不起,我没有设置 backgroundColorclearColor 解决了这个问题 . 让我留在这里,以备将来参考 .

相关问题