Make a circular button programatically - ios

I want to create a circular UIButton in my iOS application.
The button is for creating a profile picture for the user.
This is the circular profile picture:
And this is how it looks like after a picture was chosen:
You can see that the button is too big and not circular.
This is my code:
func setUpProfilePicture() {
profileIcon = UIImage(named: "characteer")!
profilePicture.setImage(profileIcon, for: .normal)
profilePicture.contentMode = .scaleAspectFill
profilePicture.addTarget(self, action: #selector(handleSelectedPhoto), for: .touchUpInside)
self.view.addSubview(profilePicture)
profilePicture.translatesAutoresizingMaskIntoConstraints = false
profilePicture.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profilePicture.topAnchor.constraint(equalTo: view.topAnchor, constant: -180).isActive = true
profilePicture.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 50).isActive = true
profilePicture.heightAnchor.constraint(equalTo: view.heightAnchor, constant: 50).isActive = true
}
The chosen picture should be just filled in the circle of the profile picture character image. I worked with auto layouts, so the most tutorials I found didn't help me!
Thank you! :)

Adjust UIButton's layer:
profilePicture.imageView.contentMode = .scaleAspectFit
let cornerRadius = 25 // 50 * 0.5
profilePicture.layer.cornerRadius = cornerRadius
profilePicture.layer.masksToBounds = true

You will need to change the corner radius of your UIButton to be half of it's size
profileIcon.imageView?.contentMode = .scaleAspectFit
profileIcon.layer.cornerRadius = min(profileIcon.frame.height, profileIcon.frame.width) / 2
profileIcon.layer.masksToBounds = true

Programmatically:
private extension UIView {
func willCircle() {
self.layer.cornerRadius = min(self.frame.size.height, self.frame.size.width) * 0.5
self.layer.masksToBounds = true
self.clipsToBounds = true
}
}
usage: profilePicture.willCircle
Storyboard:
#IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}

Related

UISegmentedControl Corner Radius Not Changing

UISegmentedControl corner radius is not changing. I also followed some answers in this question, my UISegmentedControl's corner radius still is not changing. I followed This tutorial to create UISegmentedControl.
Code:
import UIKit
class SegmentViewController: UIViewController {
private let items = ["Black", "Red", "Green"]
lazy var segmentedConrol: UISegmentedControl = {
let control = UISegmentedControl(items: items)
return control
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupViews()
}
fileprivate func setupViews(){
view.addSubview(segmentedConrol)
segmentedConrol.translatesAutoresizingMaskIntoConstraints = false //set this for Auto Layout to work!
segmentedConrol.heightAnchor.constraint(equalToConstant: 40).isActive = true
segmentedConrol.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
segmentedConrol.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -40).isActive = true
segmentedConrol.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
segmentedConrol.selectedSegmentIndex = 1
//style
segmentedConrol.layer.cornerRadius = 20
segmentedConrol.layer.borderWidth = 2
segmentedConrol.layer.borderColor = UIColor.black.cgColor
segmentedConrol.backgroundColor = .red
segmentedConrol.selectedSegmentTintColor = .darkGray
// segmentedConrol.clipsToBounds = true
segmentedConrol.layer.masksToBounds = true
}
}
(PS. Probably the answer is so simple for most people, please do not mind me, I am new in this field.)
Subclass UISegmentedControl and override layoutSubviews. Inside the method set the corner radius to what you want it to be, and you can remove the portion where you set the corner radius in setupViews():
class YourSegmentedControl: UISegmentedControl {
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = 20
}
}
In your view controller where you create segmentedControl create an instance of YourSegmentedControl like below.
lazy var segmentedConrol: YourSegmentedControl = {
let control = YourSegmentedControl(items: items)
return control
}()
The result is:

How to create a circular UIImageView

I am having issue creating a circular UIImageView. If I were to manually set the corderRadius to a value, eg. 50, it will have rounded corner. But when I try to set it as half of the frame's height or width (frame.width / 2 or frame.height / 2), it doesn't work. Somehow, the frame is (0, 0, 0, 0) when I try to print it.
And here is my code,
import UIKit
class TestIconController : UIViewController {
let icon: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = imageView.frame.width / 2
imageView.clipsToBounds = true
imageView.layer.masksToBounds = true
imageView.backgroundColor = .red
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
loadLogo()
}
func loadLogo() {
view.addSubview(icon)
// Constraints
icon.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
icon.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
icon.heightAnchor.constraint(equalToConstant: 200).isActive = true
icon.widthAnchor.constraint(equalToConstant: 200).isActive = true
}
}
Override this function.
override func viewDidLayoutSubviews() {
icon.layer.cornerRadius = icon.bounds.size.width / 2
icon.clipsToBounds = true
icon.layer.masksToBounds = true
}
You may also make a base class for it for batter handling; Like
class UICirlceImageView : UIImageView {
override open func layoutSubviews() {
super.layoutSubviews();
let layer:CALayer = self.layer;
layer.cornerRadius = self.frame.size.width/2.0;
layer.masksToBounds = true;
}
}
then, do it like this
//let icon: UICirlceImageView = { // You may initialize like this as well
let icon: UIImageView = {
let imageView = UICirlceImageView()
imageView.backgroundColor = .red
//imageView.translatesAutoresizingMaskIntoConstraints = false // Don't know if it is needed
return imageView
}()
Note: The answer given by Rushabh is also correct.
You can create this extensions
extension UIImageView {
func setRounded() {
self.layer.cornerRadius = self.frame.width / 2
self.layer.masksToBounds = true
self.clipsToBounds = true
}
}
In your case you can inside viewDidLayoutSubviews call
icon.setRounded()

iOS autolayout locating images at the same line with same ration for each views

I am working on studying iOS autolayout
However, which constraints and functions should I use for making those views have the same location.
I mean, I want to locate those two UIImageView at center like the first picture. But, whenever I change the UIView, they go down and down... what should I do?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
let firstView:UIImageView = {
let imageView = UIImageView()
imageView.image = #imageLiteral(resourceName: "angry").withRenderingMode(.alwaysOriginal)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let secondView:UIImageView = {
let imageView = UIImageView()
imageView.image = #imageLiteral(resourceName: "crying").withRenderingMode(.alwaysOriginal)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let thirdView:UIImageView = {
let imageView = UIImageView()
imageView.image = #imageLiteral(resourceName: "heartEmpty").withRenderingMode(.alwaysOriginal)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let fourthView:UIImageView = {
let imageView = UIImageView()
imageView.image = #imageLiteral(resourceName: "joy").withRenderingMode(.alwaysOriginal)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
func setupViews() {
view.addSubview(firstView)
// setup first view
firstView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
firstView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
firstView.widthAnchor.constraint(equalToConstant: 80).isActive = true
firstView.heightAnchor.constraint(equalToConstant: 80).isActive = true
view.addSubview(secondView)
// setup second view
secondView.leftAnchor.constraint(equalTo: firstView.rightAnchor, constant: 20).isActive = true
secondView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
secondView.widthAnchor.constraint(equalToConstant: 80).isActive = true
secondView.heightAnchor.constraint(equalToConstant: 80).isActive = true
view.addSubview(thirdView)
thirdView.leftAnchor.constraint(equalTo: secondView.rightAnchor, constant: 20).isActive = true
thirdView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
thirdView.widthAnchor.constraint(equalToConstant: 80).isActive = true
thirdView.heightAnchor.constraint(equalToConstant: 80).isActive = true
view.addSubview(fourthView)
fourthView.leftAnchor.constraint(equalTo: thirdView.rightAnchor, constant: 20).isActive = true
fourthView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
fourthView.widthAnchor.constraint(equalToConstant: 80).isActive = true
fourthView.heightAnchor.constraint(equalToConstant: 80).isActive = true
}
}
Hello My Friend You Can Make It By Code Or By Storyboard using stack view i will show you by code below hope this help you
import UIKit
class ViewController: UIViewController {
let firstView:UIImageView = {
let imageView = UIImageView()
imageView.image = #imageLiteral(resourceName: "MyImage").withRenderingMode(.alwaysOriginal)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let secondView:UIImageView = {
let imageView = UIImageView()
imageView.image = #imageLiteral(resourceName: "image").withRenderingMode(.alwaysOriginal)
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
func setupViews() {
view.addSubview(firstView)
// setup first view
firstView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 20).isActive = true
firstView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
firstView.widthAnchor.constraint(equalToConstant: 80).isActive = true
firstView.heightAnchor.constraint(equalToConstant: 80).isActive = true
view.addSubview(secondView)
// setup second view
secondView.leftAnchor.constraint(equalTo: firstView.rightAnchor, constant: 20).isActive = true
secondView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
secondView.widthAnchor.constraint(equalToConstant: 80).isActive = true
secondView.heightAnchor.constraint(equalToConstant: 80).isActive = true
}
}
Follow these Steps, you can do it in Storyboard.
1 - Select first Image, align it horizontally and vertically in container by giving it constraints using the "align" tab which is usually located at the bottom-right corner of the storyboard window.
2 - Now, select the first image and goto Size Inspector.Scroll down to it's constraints and there will be a constraint named as "Align Center X To : SuperView".
3 - There will be an "Edit" label right beside it.Click on it, and a popover will show up.
4 - in the popover , in the first Line it will show Constant = 0.
5 - Now here's the fun part, if you put negative value in it , say "-20" it will move 20 spaces to the left.Similarly, if you put "20", it will move 20 spaces to the right.
Now, do the same for the second image until you have achieved your result. Both the images will now be in the centre of the screen.
I am new to IOS as Well, but this worked for me and I hope it works for u as well. :-)

UIScrollViews and anchors swift

I am having trouble setting up a scroll view and actually scrolling down. I populated the scroll view with some textfields and used anchors (topanchor,leftanchor...) to position them inside the scroll view. Even if I set the scroll view height to 1000, it wont actually move, it continues to show the same items, the scroll indicator does go down but the content itself doesnt, I already set the scroll view to scrollenabled, and delegate to self.
I think the problem might be with the anchors but then how will I arrange my items inside the scroll view, any sugestion will be greatly appreaciated.
EDIT : The code below indicates the anchors applied to the scroll view ( inputContainer ), the img corresponds to an UIImageView and the mainContainer to the UIView containing the img and the inputContainer.
inputContainer.topAnchor.constraintEqualToAnchor( img.bottomAnchor ).active = true
inputContainer.leftAnchor.constraintEqualToAnchor( mainContainer.leftAnchor ).active = true
inputContainer.widthAnchor.constraintEqualToAnchor( mainContainer.widthAnchor ).active = true
inputContainerBottomConstraint = inputContainer.bottomAnchor.constraintEqualToAnchor( cancelButton.topAnchor )
inputContainerBottomConstraint?.active = true
EDIT: This is how the code looks like :
class SView : UIView, UITextFieldDelegate, UIScrollViewDelegate {
let mainContainer : UIView = {
let v = UIView()
v.backgroundColor = .whiteColor()
v.layer.cornerRadius = 8
v.layer.masksToBounds = true
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
let Img : UIImageView = {
let img = UIImageView()
img.image = UIImage(named: "noImage")
img.backgroundColor = .blueColor()
img.translatesAutoresizingMaskIntoConstraints = false
img.contentMode = .ScaleAspectFill
img.clipsToBounds = true
return img
}()
let inputContainer : UIScrollView = {
let ic = UIScrollView()
ic.backgroundColor = .whiteColor()
ic.translatesAutoresizingMaskIntoConstraints = false
return ic
}()
let datePickerTextField : UITextField = {
let tf = UITextField()
tf.placeholder = "Fecha"
tf.textAlignment = .Center
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let tagsTextField : UITextField = {
let tf = UITextField()
tf.placeholder = "Tags"
tf.textAlignment = .Center
tf.clearButtonMode = .Always
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
lazy var cancelButton : UIButton = {
let button = UIButton()
button.backgroundColor = UIColor.rgb(255, green: 65, blue: 65, alpha: 1)
button.setTitle("Cancelar", forState: .Normal)
button.tintColor = .whiteColor()
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget( self , action: #selector(handleCancelButtonPressed), forControlEvents: .TouchUpInside)
return button
}()
lazy var publicarButton : UIButton = {
let button = UIButton()
button.backgroundColor = UIColor.rgb(0 , green: 204, blue: 102, alpha: 1)
button.setTitle("Publicar", forState: .Normal)
button.tintColor = .whiteColor()
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget( self , action: #selector(handlePublicarButtonPressed), forControlEvents: .TouchUpInside)
return button
}()
override init(frame: CGRect)
{
super.init(frame: frame)
inputContainer.delegate = self
datePickerTextField.delegate = self
tagsTextField.delegate = self
setupMainContainer()
setupImg()
setupButtons()
setupInputContainer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupMainContainer ()
{
addSubview(mainContainer)
mainContainer.centerXAnchor.constraintEqualToAnchor( centerXAnchor ).active = true
mainContainer.centerYAnchor.constraintEqualToAnchor( centerYAnchor ).active = true
mainContainer.widthAnchor.constraintEqualToAnchor( widthAnchor ).active = true
mainContainer.heightAnchor.constraintEqualToAnchor( heightAnchor )
}
func setupImg ()
{
mainContainer.addSubview(Img)
Img.topAnchor.constraintEqualToAnchor( mainContainer.topAnchor ).active = true
Img.leftAnchor.constraintEqualToAnchor( mainContainer.leftAnchor ).active = true
Img.widthAnchor.constraintEqualToAnchor( mainContainer.widthAnchor ).active = true
Img.heightAnchor.constraintEqualToAnchor( mainContainer.heightAnchor , multiplier: 0.3).active = true
}
var inputContainerBottomConstraint : NSLayoutConstraint?
func setupInputContainer ()
{
mainContainer.addSubview(inputContainer)
inputContainer.topAnchor.constraintEqualToAnchor( Img.bottomAnchor ).active = true
inputContainer.leftAnchor.constraintEqualToAnchor( mainContainer.leftAnchor ).active = true
inputContainer.rightAnchor.constraintEqualToAnchor( mainContainer.rightAnchor ).active = true
inputContainerBottomConstraint = inputContainer.bottomAnchor.constraintEqualToAnchor( cancelButton.topAnchor )
inputContainerBottomConstraint?.active = true
inputContainer.addSubview( datePickerTextField )
inputContainer.addSubview( tagsTextField )
datePickerTextField.topAnchor.constraintEqualToAnchor( inputContainer.topAnchor ).active = true
datePickerTextField.centerXAnchor.constraintEqualToAnchor( inputContainer.centerXAnchor ).active = true
datePickerTextField.widthAnchor.constraintEqualToAnchor( inputContainer.widthAnchor ).active = true
datePickerTextField.heightAnchor.constraintEqualToAnchor( inputContainer.heightAnchor, multiplier: 0.2 ).active = true
tagsTextField.bottomAnchor.constraintEqualToAnchor( inputContainer.bottomAnchor ).active = true
tagsTextField.centerXAnchor.constraintEqualToAnchor( inputContainer.centerXAnchor ).active = true
tagsTextField.widthAnchor.constraintEqualToAnchor( inputContainer.widthAnchor ).active = true
tagsTextField.heightAnchor.constraintEqualToAnchor( inputContainer.heightAnchor, multiplier: 0.2 ).active = true
}
func setupButtons()
{
mainContainer.addSubview( cancelButton )
mainContainer.addSubview( publicarButton )
cancelButton.bottomAnchor.constraintEqualToAnchor( mainContainer.bottomAnchor).active = true
cancelButton.leftAnchor.constraintEqualToAnchor( mainContainer.leftAnchor ).active = true
cancelButton.widthAnchor.constraintEqualToAnchor( mainContainer.widthAnchor, multiplier: 0.5 ).active = true
cancelButton.heightAnchor.constraintEqualToAnchor( mainContainer.heightAnchor, multiplier: 0.1).active = true
publicarButton.bottomAnchor.constraintEqualToAnchor( mainContainer.bottomAnchor).active = true
publicarButton.leftAnchor.constraintEqualToAnchor( cancelButton.rightAnchor ).active = true
publicarButton.widthAnchor.constraintEqualToAnchor( mainContainer.widthAnchor, multiplier: 0.5 ).active = true
publicarButton.heightAnchor.constraintEqualToAnchor( mainContainer.heightAnchor, multiplier: 0.1).active = true
} }
So when the keyboard appears the bottom anchor constant of the scroll view changes so that the keyboard "top anchor" is the new bottom anchor.
With the constraints you have described there's no way for the layout engine to determine the content height of the scroll view. You should pin your bottom text field to the bottom of the scroll view. This way the scroll view's content size will resize up to the max y of all of the text fields. Here is some code you can put in a playground to see:
import UIKit
import XCPlayground
let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 200, height: 150))
scrollView.backgroundColor = UIColor.whiteColor()
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.backgroundColor = UIColor.purpleColor()
let otherTextField = UITextField()
otherTextField.translatesAutoresizingMaskIntoConstraints = false
otherTextField.backgroundColor = UIColor.purpleColor()
let otherOtherTextField = UITextField()
otherOtherTextField.translatesAutoresizingMaskIntoConstraints = false
otherOtherTextField.backgroundColor = UIColor.purpleColor()
scrollView.addSubview(textField)
textField.topAnchor.constraintEqualToAnchor(scrollView.topAnchor).active = true
textField.leadingAnchor.constraintEqualToAnchor(scrollView.leadingAnchor).active = true
textField.widthAnchor.constraintEqualToAnchor(scrollView.widthAnchor).active = true
scrollView.addSubview(otherTextField)
otherTextField.topAnchor.constraintEqualToAnchor(textField.bottomAnchor, constant: 60).active = true
otherTextField.leadingAnchor.constraintEqualToAnchor(scrollView.leadingAnchor).active = true
otherTextField.widthAnchor.constraintEqualToAnchor(scrollView.widthAnchor).active = true
scrollView.addSubview(otherOtherTextField)
otherOtherTextField.topAnchor.constraintEqualToAnchor(otherTextField.bottomAnchor, constant: 60).active = true
otherOtherTextField.leadingAnchor.constraintEqualToAnchor(scrollView.leadingAnchor).active = true
otherOtherTextField.widthAnchor.constraintEqualToAnchor(scrollView.widthAnchor).active = true
otherOtherTextField.bottomAnchor.constraintEqualToAnchor(scrollView.bottomAnchor).active = true
scrollView.setNeedsLayout()
XCPlaygroundPage.currentPage.liveView = scrollView
This places three text fields in a scroll view with 60 points between the center and top and bottom. If you comment out:
otherOtherTextField.bottomAnchor.constraintEqualToAnchor(scrollView.bottomAnchor).active = true
The scroll view in the assistant editor will not scroll, but with it it does.

How to set imageView in circle like imageContacts in Swift correctly?

I want to show a picture into imageView like the image contact (in a circle) But when I try to show this, the imageView rescale his size and this doesn't show correctly in a circle.
image.layer.borderWidth=1.0
image.layer.masksToBounds = false
image.layer.borderColor = UIColor.whiteColor().CGColor
image.layer.cornerRadius = image.frame.size.height/2
image.clipsToBounds = true
I want to show like this:
But I get this:
How can do the image resize to UIImageView size to show as a circle?
Thanks!
This is solution which I have used in my app:
var image: UIImage = UIImage(named: "imageName")
imageView.layer.borderWidth = 1.0
imageView.layer.masksToBounds = false
imageView.layer.borderColor = UIColor.whiteColor().CGColor
imageView.layer.cornerRadius = image.frame.size.width/2
imageView.clipsToBounds = true
Swift 4.0
let image = UIImage(named: "imageName")
imageView.layer.borderWidth = 1.0
imageView.layer.masksToBounds = false
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.cornerRadius = image.frame.size.width / 2
imageView.clipsToBounds = true
What frame size are you using for image? I can get a perfect circle if I set the frame to be a square.
let image = UIImageView(frame: CGRectMake(0, 0, 100, 100))
Fast and Simple solution.
How to mask UIImage to Circle without cropping with Swift.
extension UIImageView {
public func maskCircle(anyImage: UIImage) {
self.contentMode = UIViewContentMode.ScaleAspectFill
self.layer.cornerRadius = self.frame.height / 2
self.layer.masksToBounds = false
self.clipsToBounds = true
// make square(* must to make circle),
// resize(reduce the kilobyte) and
// fix rotation.
self.image = anyImage
}
}
How to call:
let anyAvatarImage:UIImage = UIImage(named: "avatar")!
avatarImageView.maskCircle(anyAvatarImage)
Try this it's work for me ,
set imageView width and height same .
Swift
imageview?.layer.cornerRadius = (imageview?.frame.size.width ?? 0.0) / 2
imageview?.clipsToBounds = true
imageview?.layer.borderWidth = 3.0
imageview?.layer.borderColor = UIColor.white.cgColor
Screenshot
Objective C
self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2;
self.imageView.clipsToBounds = YES;
self.imageView.layer.borderWidth = 3.0f;
self.imageView.layer.borderColor = [UIColor whiteColor].CGColor;
Hope this will help to some one .
Create your custom circle UIImageView and create the circle under the layoutSubviews helps if you use Autolayout.
/*
+-------------+
| |
| |
| |
| |
| |
| |
+-------------+
The IMAGE MUST BE SQUARE
*/
class roundImageView: UIImageView {
override init(frame: CGRect) {
// 1. setup any properties here
// 2. call super.init(frame:)
super.init(frame: frame)
// 3. Setup view from .xib file
}
required init?(coder aDecoder: NSCoder) {
// 1. setup any properties here
// 2. call super.init(coder:)
super.init(coder: aDecoder)
// 3. Setup view from .xib file
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.borderWidth = 1
self.layer.masksToBounds = false
self.layer.borderColor = UIColor.white.cgColor
self.layer.cornerRadius = self.frame.size.width/2
self.clipsToBounds = true
}
}
I would suggest making your image file a perfect square to begin with. This can be done in almost any photo editing program. After that, this should work within viewDidLoad. Credit to this video
image.layer.cornerRadius = image.frame.size.width/2
image.clipsToBounds = true
That is all you need....
profilepic = UIImageView(frame: CGRectMake(0, 0, self.view.bounds.width * 0.19 , self.view.bounds.height * 0.1))
profilepic.layer.borderWidth = 1
profilepic.layer.masksToBounds = false
profilepic.layer.borderColor = UIColor.blackColor().CGColor
profilepic.layer.cornerRadius = profilepic.frame.height/2
profilepic.clipsToBounds = true
this extension really works for me (including in swift 4+)
extension UIImageView {
func roundedImage() {
self.layer.cornerRadius = (self.frame.size.width) / 2;
self.clipsToBounds = true
self.layer.borderWidth = 3.0
self.layer.borderColor = UIColor.white.cgColor
}
}
Then simply call it as
imageView.roundedImage()
If your using a UIViewController here's how do do it using Anchors. The key is to set the imageView's layer.cornerRadius in viewWillLayoutSubviews like so:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
imageView.layer.cornerRadius = imageView.frame.size.width / 2
}
Also make sure the heightAnchor and widthAnchor are the same size. They are both 100 in my example below
Code:
let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.layer.borderWidth = 1.0
imageView.clipsToBounds = true
imageView.layer.borderColor = UIColor.white.cgColor
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(imageView)
imageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 100).isActive = true
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50).isActive = true
imageView.image = UIImage(named: "pizzaImage")
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
imageView.layer.cornerRadius = imageView.frame.size.width / 2
}
If your using a CollectionView Cell set the imageView's layer.cornerRadius in layoutSubviews():
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
imageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 100).isActive = true
imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 50).isActive = true
imageView.image = UIImage(named: "pizzaImage")
}
override func layoutSubviews() {
super.layoutSubviews() // call super.layoutSubviews()
imageView.layer.cornerRadius = imageView.frame.size.width / 2
}
reviewerImage.layer.cornerRadius = reviewerImage.frame.size.width / 2;
reviewerImage.clipsToBounds = true
what i found out is that your width and height of image view must return an even number when divided by 2 to get a perfect circle e.g
let image = UIImageView(frame: CGRectMake(0, 0, 120, 120))
it should not be something like
let image = UIImageView(frame: CGRectMake(0, 0, 130, 130))
I had a similar result (more of an oval than a circle). It turned out that the constraints I set on the UIImageView forced it into an oval instead of a circle. After fixing that, the above solutions worked.
try this.
swift code
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
perform(#selector(self.setCircleForImage(_:)), with: pickedImage, afterDelay: 0)
}
#objc func setCircleForImage(_ imageView : UIImageView){
imageView.layer.cornerRadius = pickedImage.frame.size.width/2
imageView.clipsToBounds = true
}
I fixed it doing modifying the view:
Go to your Main.storyboard
Click on your image
View -> Mode -> Aspect Fill
It works perfectly
This work perfectly for me.
The order of lines is important
func circularImage(photoImageView: UIImageView?)
{
photoImageView!.layer.frame = CGRectInset(photoImageView!.layer.frame, 0, 0)
photoImageView!.layer.borderColor = UIColor.grayColor().CGColor
photoImageView!.layer.cornerRadius = photoImageView!.frame.height/2
photoImageView!.layer.masksToBounds = false
photoImageView!.clipsToBounds = true
photoImageView!.layer.borderWidth = 0.5
photoImageView!.contentMode = UIViewContentMode.ScaleAspectFill
}
How to use:
#IBOutlet weak var photoImageView: UIImageView!
...
...
circularImage(photoImageView)
This also works for me. For perfect circle result, use the same size for width and height. like image.frame = CGRect(0,0,200, 200)
For non perfect circle, width and height should not be equal like this codes below.
image.frame = CGRect(0,0,200, 160)
image.layer.borderColor = UIColor.whiteColor().CGColor
image.layer.cornerRadius = image.frame.size.height/2
image.layer.masksToBounds = false
image.layer.clipsToBounds = true
image.contentMode = .scaleAspectFill
Use this code to make image round
self.layoutIfNeeded()
self.imageView.layer.cornerRadius =
self.imageView.frame.width/2
self.imageView.layer.masksToBounds = true
You can add this file extension to your project & Don't forget to make your image Square "Width = Height" and you can grantee it by giving the image width and Aspect Ratio (1:1)
import Foundation
import UIKit
extension UIView {
#IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
#IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
#IBInspectable
var borderColor: UIColor? {
get {
let color = UIColor(cgColor: layer.borderColor!)
return color
}
set {
layer.borderColor = newValue?.cgColor
}
}
}
Then you will write this line in the cell or view controller or wherever you use your image:
imageViewCountryImage.cornerRadius = imageViewCountryImage.frame.height / 2
and you will find your image very super circular
// MARK: ImageView extension to make rounded
#IBDesignable extension UIImageView {
#IBInspectable var masksToBounds: Bool {
set {
layer.masksToBounds = newValue
}
get {
return layer.masksToBounds
}
}
#IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
#IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
#IBInspectable var borderColor: UIColor? {
set {
guard let uiColor = newValue else { return }
layer.borderColor = uiColor.cgColor
}
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
}
}
You need to make sure the height and width should be the same as your image/view.
Like an image with 100 widths and 100 height sizes (100 X 100). If the sizes are different then the circle does not look like a circle.
You can add this extension to your code
import Foundation
import UIKit
extension UIView {
#IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
#IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
#IBInspectable
var borderColor: UIColor? {
get {
let color = UIColor(cgColor: layer.borderColor!)
return color
}
set {
layer.borderColor = newValue?.cgColor
}
}
}
Just add this extension
Extension:
extension UIImageView {
func circleImageView() {
layer.borderColor = UIColor.white.cgColor
layer.borderWidth = 2
contentMode = .scaleAspectFill
layer.cornerRadius = self.frame.height / 2
layer.masksToBounds = false
clipsToBounds = true
}
}
Controller:
self.imageView?.circleImageView()
One more thing, in order to make the image circle we've to set both width and height equal to each other.
Make sure that your height and width of your UIImageView is equal, or else it will look elliptical.
I have solved this problem with using these codes
private let profileAvatarImageView: UIImageView = {
let imageView = UIImageView()
imageView.clipsToBounds = true
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = imageView.frame.width/2
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.image = UIImage(systemName: "person")
imageView.backgroundColor = .black
imageView.layer.borderWidth = 2.0
imageView.layer.borderColor = UIColor.black.cgColor
return imageView
}()

Resources