how to make a gradient border of UIView?

后端 未结 6 1122
遇见更好的自我
遇见更好的自我 2020-12-28 17:37

I want to make a gradient border of view like the following picture:

\"Image\"

but I don\'t know how d

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-28 18:17

    Here is how you would do it with Core Graphics. Create a UIView subclass and in its drawRect: create a gradient and overlay that with a black content rectangle:

    - (void)drawRect:(CGRect)rect
    {
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
        // Create and draw the gradient
        UIColor *gradientColorTop = [UIColor orangeColor];
        UIColor *gradientColorBottom = [UIColor yellowColor];
        NSArray *gradientColors = @[(id) gradientColorTop.CGColor, (id) gradientColorBottom.CGColor];
        CGFloat locations[] = {0.1, 0.80};
    
        CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)(gradientColors), locations);
    
        CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
        CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
    
        UIBezierPath *gradientBorder = [UIBezierPath bezierPathWithRoundedRect:rect
        byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10.0, 10.0)];
        [gradientBorder addClip];
    
        CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0);
    
        // Draw the inner content rectangle
        UIBezierPath *contentPath = [UIBezierPath bezierPathWithRect:CGRectInset(rect, 20.0, 20.0)];
        [[UIColor blackColor] setFill];
        [contentPath fill];
    
        CGGradientRelease(gradient);
        CGColorSpaceRelease(colorSpace);
    }
    

    That would produce a result similar to what you are trying to achieve.

提交回复
热议问题