I'm aware that the formulae frame.size.width/2
should produce a circle border, however in XCode I am currently experiencing some discrepancies.
I have two test devices (iPhone6 and 5th gen iPod touch) I also have the simulator running. Both my devices display correctly but the simulator draws my circle as a rounded rectangle:
The code I am using to achieve this (although very simple) is:
imgAvatar.layer.masksToBounds = true
imgAvatar.clipsToBounds = true
imgAvatar.layer.cornerRadius = imgAvatar.frame.size.width/2
imgAvatar.layer.borderWidth = 5
imgAvatar.layer.borderColor = UIColor.whiteColor().CGColor
Is there any reason why this is happening? It's driving me insane!
UPDATE To clear confusion, the UIImageView
is declared in my storyboard as 190x190
it also has a 1:1
aspect ratio constraint applied to it to ensure it maintains a proportional width and height.
UPDATE 2 To put any suspicions regarding my auto-layout constraints to bed, I have attached the below image which shows the constraints set for imgAvatar
. As you can see a the width and height match and the AR is set to ensure it maintains that 1:1 ratio. I hope that clears up any further doubts
ANSWER Leo pointed out an extremely practical and reusable solution to fix this problem, using Swift extensions one can ensure that a given UIImage is always square, thus always generating a circle, I have posted Leo's solution below:
extension UIImage {
var circleMask: UIImage? {
let square = CGSize(width: min(size.width, size.height), height: min(size.width, size.height))
let imageView = UIImageView(frame: .init(origin: .init(x: 0, y: 0), size: square))
imageView.contentMode = .scaleAspectFill
imageView.image = self
imageView.layer.cornerRadius = square.width/2
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.borderWidth = 5
imageView.layer.masksToBounds = true
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
imgAvatar.image = yourImage.circleMask
imgFrame
, as well as the resultingcornerRadius
property? (Note thatNSStringFromCGRect()
might be helpful here.) – ChillerinitFrames
which is called inviewDidLoad
– SchoolboyviewDidLoad
is too soon. The view controller's view isn't sized yet. TryviewWillAppear:
. – DarbyviewWillAppear
seeing the same results – Schoolboy