iOS绘图之画一个渐变的Border

天才小飞猫

clipboard.png

- (void) drawRect:(CGRect)rect
    {
        CGFloat colors [] = {
            1.0, 0.0, 0.0, 1.0,
            1.0, 1.0, 0.0, 1.0,
            0.0, 1.0, 0.0, 1.0,
            0.0, 1.0, 1.0, 1.0,
            0.0, 0.0, 1.0, 1.0,
            1.0, 0.0, 1.0, 1.0
        };

        
        CGRect mapRect = CGRectIntegral(CGRectInset(rect, 100, 250));
        CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
        CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 6);
        CGColorSpaceRelease(baseSpace), baseSpace = NULL;
        
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        CGContextSetLineWidth(context, 4);
        CGContextSetLineJoin(context, kCGLineJoinRound);
        CGContextSetLineCap(context, kCGLineCapRound);
        
        CGContextAddPath(context, CGPathCreateWithRoundedRect(mapRect, 16, 16, NULL));
        CGContextReplacePathWithStrokedPath(context);
        CGContextClip(context);

        // Define the start and end points for the gradient
        // This determines the direction in which the gradient is drawn
        CGPoint startPoint = CGPointMake(CGRectGetMidX(mapRect), CGRectGetMinY(mapRect));
        CGPoint endPoint = CGPointMake(CGRectGetMidX(mapRect), CGRectGetMaxY(mapRect));
        
        CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
        CGGradientRelease(gradient), gradient = NULL;
    }
    
阅读 5k

320 声望
16 粉丝
0 条评论
320 声望
16 粉丝
文章目录
宣传栏