径向渐变:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
//创建一个RGB的颜色空间
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
//定义渐变颜色数组
CGFloat colors[] =
{
0.0f, 0.0f, 0.0f, 0.3f,
0.0f, 0.0f, 0.0f, 0.1f,
0.0f, 0.0f, 0.0f, 0.3f
};
const CGFloat locations[3] = { 0.0f, 0.5f, 1.0f };
//创建一个渐变的色值 1:颜色空间 2:渐变的色数组 3:位置数组,如果为NULL,则为平均渐变,否则颜色和位置一一对应 4:位置的个数
CGGradientRef _gradient = CGGradientCreateWithColorComponents(rgb, colors, locations, sizeof(colors)/(sizeof(colors[0])*4));
CGColorSpaceRelease(rgb);
//获得一个CGRect
//CGRect clip = CGRectInset(CGContextGetClipBoundingBox(ctx), 20.0, 20.0);
//剪切到合适的大小
//CGContextClipToRect(ctx, clip);
//定义起始点和终止点
CGPoint start = CGPointMake(CGRectGetMinX(self.bounds), CGRectGetMinY(self.bounds));
CGPoint end = CGPointMake(CGRectGetMinX(self.bounds), CGRectGetMaxY(self.bounds));
//绘制渐变, 颜色的0对应start点,颜色的1对应end点,第四个参数是定义渐变是否超越起始点和终止点
CGContextDrawLinearGradient(ctx, _gradient, start, end, kCGGradientDrawsBeforeStartLocation);
}
圆形辐射渐变
- (void)drawRect:(CGRect)rect
{
const CGFloat components[8] = { 0.0f, 0.0f, 0.0f, 0.3f, 0.0f, 0.0f, 0.0f, 0.7f };
const CGFloat locations[2] = { 0.0f, 1.0f };
CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(space, components, locations, 2);
CGColorSpaceRelease(space);
CGFloat x = CGRectGetMidX(self.bounds);
CGFloat y = CGRectGetMidY(self.bounds);
CGPoint point = CGPointMake(x, y);
CGFloat radius = MAX(x, y);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextDrawRadialGradient(context, gradient, point, 0, point, radius, kCGGradientDrawsAfterEndLocation);
CGGradientRelease(gradient);
}
网友评论