Faisal Syed Faisal Syed - 1 month ago 16
Swift Question

How to find radius of image view?

I currently have an image view that contains a circular image.

I've set it up like so:

profileImageView.layer.cornerRadius = self.profileImageView.frame.size.width / 2
profileImageView.clipsToBounds = true


I'm attempting to draw an arc around the circle using UIBezierPath, and I would like to pass the radius of the Image View for the radius parameter.

let circlePath = UIBezierPath(arcCenter: CGPoint(x: profileImageView.frame.size.width/2, y: profileImageView.frame.size.height/2), radius: IMG_VIEW_RADIUS, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)


How would I go about doing that?

Answer

Swift 3.0

Another way

I just added a imageView like this

let imageView = UIImageView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
imageView.backgroundColor = UIColor.green
imageView.layer.cornerRadius = imageView.frame.size.width / 2
imageView.clipsToBounds = true
self.view.addSubview(imageView)

Doing the circular bezier path

let circlePath = UIBezierPath(arcCenter: CGPoint(x: imageView.frame.size.width/2,y: imageView.frame.size.height/2), radius: CGFloat(imageView.frame.size.width/2), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath

//fill color
shapeLayer.fillColor = UIColor.clear.cgColor

//stroke color
shapeLayer.strokeColor = UIColor.white.cgColor

//line width
shapeLayer.lineWidth = 1.0

//finally adding the shapeLayer to imageView's layer
imageView.layer.addSublayer(shapeLayer)

Now creating an outside border using the same concept

 let outerCirclePath = UIBezierPath(arcCenter: CGPoint(x: imageView.frame.size.width/2,y: imageView.frame.size.height/2), radius: CGFloat(imageView.frame.size.width/2 ), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
let outerLayer = CAShapeLayer()
outerLayer.path = outerCirclePath.cgPath

//fill color
outerLayer.fillColor = UIColor.clear.cgColor
//stroke color
outerLayer.strokeColor = UIColor.blue.cgColor
//line width
outerLayer.lineWidth = 15.0
imageView.layer.addSublayer(outerLayer)

Now change the zPosition of shape layer created for the innerLayer

shapeLayer.zPosition = 2

enter image description here

Comments