iPhone 6 iPhone 6 - 4 months ago 24
iOS Question

How to set gradient color to UIImageView border

How to apply gradient color to UIImageView border color. What i tried is

let gradient: CAGradientLayer = CAGradientLayer()

let color0 = UIColor(red:0.0/255, green:0.0/255, blue:0.0/255, alpha:0.0).CGColor
let color1 = UIColor(red:0.0/255, green:0.0/255, blue: 0.0/255, alpha:0.71).CGColor

gradient.colors = [color0, color1]
gradient.locations = [0.0 , 1.0]
gradient.frame = CGRect(x: 0.0, y: 80.0, width: self.imgProfile.frame.size.width, height: self.imgProfile.frame.size.height-35)

self.imgProfile.layer.insertSublayer(gradient, atIndex: 0)


This is what required

enter image description here

Please guide, thanks

Update:

Tried this way

let gradient = CAGradientLayer()
gradient.frame = CGRect(origin: CGPointZero, size: self.imgPeopleProfile.frame.size)
gradient.colors = [UIColor.blueColor().CGColor, UIColor.greenColor().CGColor]

let shape = CAShapeLayer()
shape.lineWidth = 2
shape.path = UIBezierPath(rect: self.imgPeopleProfile.bounds).CGPath
shape.strokeColor = UIColor.blackColor().CGColor
shape.fillColor = UIColor.clearColor().CGColor
gradient.mask = shape

imgPeopleProfile.layer.cornerRadius = imgPeopleProfile.frame.size.width / 2
imgPeopleProfile.clipsToBounds = true
self.imgPeopleProfile.layer.addSublayer(gradient)


It gives enter image description here

enter image description here

Answer

Please take Imageview Size Equal width and height ex. Width=100 and Height = 100 So it will show proper Circle. If you want to change the Size then please amke also change in the below Line .

shape.path = UIBezierPath(arcCenter: CGPoint(x: 50, y: 50), radius: CGFloat(50), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true).CGPath

With the radius of the Circle in above example its 50.

 let gradient = CAGradientLayer()
            gradient.frame =  CGRect(origin: CGPointZero, size: self.imageView.frame.size)
            gradient.colors = [UIColor(red:87.0/255, green:206.0/255, blue: 172.0/255, alpha:0.71).CGColor,UIColor(red:44.0/255, green:192.0/255, blue:208.0/255, alpha:1.0).CGColor]

            imageView.layer.cornerRadius = imageView.frame.size.width / 2
            imageView.clipsToBounds = true

            let shape = CAShapeLayer()
            shape.lineWidth = 5
            shape.path = UIBezierPath(arcCenter: CGPoint(x: 50, y: 50), radius: CGFloat(50), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true).CGPath
            shape.strokeColor = UIColor.blackColor().CGColor
            shape.fillColor = UIColor.clearColor().CGColor
            gradient.mask = shape

            self.imageView.layer.addSublayer(gradient)

enter image description here