我正在CGGradientRef
使用CGGradientCreateWithColorComponents创建,它被记录为支持 alpha 通道:
此数组中的项目数应该是计数和颜色空间中组件数的乘积。例如,如果颜色空间是 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
问题是似乎不支持透明度,透明部分被淹没为白色:
CGGradientRef
是否可以通过使“较低”子视图部分可见来获得透明度?