iOS绘图之画一个渐变的Border

iOS绘图之画一个渐变的Border

- (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;
    }