IOS_使用CGContextRef实现线性渐变和圆弧遮罩

来源:互联网 发布:音乐变成伴奏软件 编辑:程序博客网 时间:2024/04/29 01:00

本来再次来自本群 【天空air_as3_北京】 仰慕者可以给作者发email:paradiselwh154@gmail.com 

顺便介绍我们的QQ群:241465868 


源代码在此,请点击下载Demo


原理:使用了遮罩,核心就是:

    CGImageRef mask = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext());    UIGraphicsEndImageContext();        CGContextClipToMask(ctx, self.bounds, mask);    CGImageRelease(mask);


代码片段如下:

- (void)drawRect:(CGRect)rect{    [super drawRect:rect];        CGContextRef ctx = UIGraphicsGetCurrentContext();        UIGraphicsBeginImageContext(CGSizeMake(100,100));    CGContextRef imageCtx = UIGraphicsGetCurrentContext();        CGContextAddArc(imageCtx, self.frame.size.width/2  , self.frame.size.height/2, 25, 0, 2*M_PI, 0);    [[UIColor redColor]set];        CGContextSetShadowWithColor(imageCtx, CGSizeMake(0, 0), 2*M_PI/20, [UIColor whiteColor].CGColor);        CGContextSetLineWidth(imageCtx, 10);    CGContextDrawPath(imageCtx, kCGPathStroke);            CGImageRef mask = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext());    UIGraphicsEndImageContext();            CGContextClipToMask(ctx, self.bounds, mask);    CGImageRelease(mask);            CGFloat components[8] = {        0.0, 0.0, 0.0, 1.0,        1.0, 1.0, 1.0, 1.0 };        CGColorSpaceRef cg = CGColorSpaceCreateDeviceRGB();    CGGradientRef gradient = CGGradientCreateWithColorComponents(cg, components, NULL, 2);    CGColorSpaceRelease(cg), cg = NULL;        CGPoint startPoint = CGPointMake(0, 0);    CGPoint endPoint = CGPointMake(100, 100);        CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0);    CGGradientRelease(gradient), gradient = NULL;}

运行结果如下:




小编:

已经是 【天空Air兄】的第三篇文了,你是要闹哪样。不过期待更全面讲解的博文,稍稍多写写理论,再附上Code就更完美了。

原创粉丝点击