Skip to content

Instantly share code, notes, and snippets.

@leilee
Created September 21, 2017 09:31
Show Gist options
  • Save leilee/b3c057615724df34426837a0f70222d0 to your computer and use it in GitHub Desktop.
Save leilee/b3c057615724df34426837a0f70222d0 to your computer and use it in GitHub Desktop.
Add gradient border to UIView
#import <UIKit/UIKit.h>
@interface UIView (UPGradientBorder)
- (void)up_setHorizontalGradientBorderWithColors:(NSArray<UIColor*>*)colors borderWidth:(CGFloat)borderWidth;
- (void)up_setVerticalGradientBorderWithColors:(NSArray<UIColor*>*)colors borderWidth:(CGFloat)borderWidth;
- (void)up_setGradientBorderWithColors:(NSArray<UIColor*>*)colors borderWidth:(CGFloat)borderWidth startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint;
- (void)up_removeGradientBorder;
@end
#import "UIView+UPGradientBorder.h"
static NSString* const kLayerNameGradientBorder = @"UPGradientBorderLayer";
@implementation UIView (UPGradientBorder)
- (void)up_setHorizontalGradientBorderWithColors:(NSArray<UIColor*>*)colors borderWidth:(CGFloat)borderWidth
{
[self up_setGradientBorderWithColors:colors borderWidth:borderWidth startPoint:{0, 0.5} endPoint:{1, 0.5}];
}
- (void)up_setVerticalGradientBorderWithColors:(NSArray<UIColor*>*)colors borderWidth:(CGFloat)borderWidth
{
[self up_setGradientBorderWithColors:colors borderWidth:borderWidth startPoint:{0.5, 0} endPoint:{0.5, 1}];
}
- (void)up_setGradientBorderWithColors:(NSArray<UIColor*>*)colors borderWidth:(CGFloat)borderWidth startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint
{
auto existedBorder = [self gradientBorderLayer];
auto border = existedBorder ?: CAGradientLayer.layer;
border.name = kLayerNameGradientBorder;
border.frame = self.bounds;
border.startPoint = startPoint;
border.endPoint = endPoint;
auto cgColors = [NSMutableArray array];
for (UIColor* c in colors)
{
[cgColors addObject:((__bridge id)c.CGColor)];
}
border.colors = cgColors;
auto mask = CAShapeLayer.layer;
mask.path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:0].CGPath;
mask.fillColor = UIColor.clearColor.CGColor;
mask.strokeColor = UIColor.whiteColor.CGColor;
mask.lineWidth = borderWidth;
border.mask = mask;
auto exists = existedBorder != nil;
if (!exists)
{
[self.layer addSublayer:border];
}
}
- (void)up_removeGradientBorder
{
[self.gradientBorderLayer removeFromSuperlayer];
}
- (CAGradientLayer*)gradientBorderLayer
{
for (CALayer* l in self.layer.sublayers)
{
if ([l.name isEqualToString:kLayerNameGradientBorder])
{
return OBJC_DYNAMIC_CAST(l, CAGradientLayer);
}
}
return nil;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment