how to make a gradient border of UIView?

remykits picture remykits · Mar 4, 2013 · Viewed 11.3k times · Source

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

Image

but I don't know how do it exactly , i.e. what the gradient color I should use to do it? how to set my view to show a border like the image?

I'm using the following code to get a border:

 self.view.layer.borderColor = [UIColor orangeColor].CGColor;
 self.view.layer.borderWidth = 2.0f;

Answer

Christos Chadjikyriacou picture Christos Chadjikyriacou · Nov 19, 2015

This what i did and it worked perfectly

   extension CALayer {
    func addGradienBorder(colors:[UIColor],width:CGFloat = 1) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame =  CGRect(origin: CGPointZero, size: self.bounds.size)
        gradientLayer.startPoint = CGPointMake(0.0, 0.5)
        gradientLayer.endPoint = CGPointMake(1.0, 0.5)
        gradientLayer.colors = colors.map({$0.CGColor})

        let shapeLayer = CAShapeLayer()
        shapeLayer.lineWidth = width
        shapeLayer.path = UIBezierPath(rect: self.bounds).CGPath
        shapeLayer.fillColor = nil
        shapeLayer.strokeColor = UIColor.blackColor().CGColor
        gradientLayer.mask = shapeLayer

        self.addSublayer(gradientLayer)
    }

}