IOS_使用CGContextRef實現線性漸變和圓弧遮罩

本來再次來自本羣 【天空air_as3_北京】 仰慕者可以給作者發email:[email protected] 

順便介紹我們的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就更完美了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章