How to create a circular UIImageView - ios

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()

Related

How to set the corner radius to 50% [duplicate]

This question already has answers here:
Set UIView's corner radius to half of the view's width automatically
(3 answers)
Closed 11 months ago.
I have an image view inside a collection view cell. I would like to set the corner radius of the image to 50% of its width (so it's a circle). How can I do this?
Here's my code so far
//
// CategoryCell.swift
// UICollectionViewDemo
//
import UIKit
final class Category3Cell: UICollectionViewCell {
private enum Constants {
// MARK: contentView layout constants
static let contentViewCornerRadius: CGFloat = 0.0
// MARK: imageView layout constants
static let imageWidth: CGFloat = 90.0
static let imageHeight: CGFloat = 90.0
// MARK: Generic layout constants
static let verticalSpacing: CGFloat = 10.0
static let horizontalPadding: CGFloat = 16.0
static let nameImagePadding: CGFloat = 20.0
}
public var categoryKey : String = "";
private let imageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.contentMode = .scaleAspectFit
imageView.layer.cornerRadius = 45
imageView.layer.masksToBounds = true
return imageView
}()
private let name: UILabel = {
let label = UILabel(frame: .zero)
label.textAlignment = .center
label.numberOfLines = 0
label.font = UIFont(name: "CeraPro-Regular", size: 17);
return label
}()
override init(frame: CGRect) {
super.init(frame: .zero)
setupViews()
setupLayouts()
}
private func setupViews() {
contentView.clipsToBounds = true
contentView.layer.cornerRadius = Constants.contentViewCornerRadius
contentView.backgroundColor = .clear
contentView.isUserInteractionEnabled = true
contentView.addSubview(imageView)
contentView.addSubview(name)
}
private func setupLayouts() {
imageView.translatesAutoresizingMaskIntoConstraints = false
name.translatesAutoresizingMaskIntoConstraints = false
// Layout constraints for `imageView`
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
imageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
imageView.topAnchor.constraint(equalTo: contentView.topAnchor),
imageView.heightAnchor.constraint(equalToConstant: Constants.imageWidth),
imageView.heightAnchor.constraint(equalToConstant: Constants.imageHeight)
])
// Layout constraints for `usernameLabel`
NSLayoutConstraint.activate([
name.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: Constants.horizontalPadding),
name.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -Constants.horizontalPadding),
name.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: Constants.nameImagePadding)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(image: String, nameOf: String, key: String) {
imageView.image = UIImage.init(named: image)
name.text = nameOf
categoryKey = key
}
}
extension Category3Cell: ReusableView {
static var identifier: String {
return String(describing: self)
}
}
you need first the clipsToBounds set to true and then if you know the image size, you can set its layer.cornerRadius to half of that size.
Alternatively you can use the layoutSubviews method, and in its override access the imageView bounds.height and use half of this for the corner radius.
Try this code:
imageView.layer.cornerRadius = imageView.frame.height / 2
Set width and height at first, then set imageView.layer.cornerRadius = imageView.frame.height / 2.
class ViewController: UIViewController {
private let imageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.contentMode = .scaleAspectFit
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
imageView.frame = CGRect(x: 100, y: 100, width: 100, height: 100);
imageView.layer.cornerRadius = 45
imageView.layer.masksToBounds = true
self.view.addSubview(imageView)
imageView.image = UIImage.init(named: "+")
}
}

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:

Mask UIView with another UIView

Yes this question has been asked before, the solutions did not work or had different applications.
It is the most basic setup. I have two rectangular UIViews, red and blue.
I would like the blue square to cut into the red square, so the red square looks like an "L"
import Foundation
import UIKit
class TestController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = .gray
view.addSubview(viewA)
view.addSubview(maskView)
viewA.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
viewA.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
viewA.widthAnchor.constraint(equalToConstant: 100).isActive = true
viewA.heightAnchor.constraint(equalToConstant: 100).isActive = true
viewA.translatesAutoresizingMaskIntoConstraints = false
maskView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 50).isActive = true
maskView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -50).isActive = true
maskView.widthAnchor.constraint(equalToConstant: 100).isActive = true
maskView.heightAnchor.constraint(equalToConstant: 100).isActive = true
maskView.translatesAutoresizingMaskIntoConstraints = false
// Things which don't work
//viewA.mask = maskView // both views disappear
//viewA.layer.mask = maskView.layer // both views disappear
//viewA.layer.addSublayer(maskView.layer) // hides mask view
}
var viewA: UIView = {
let view = UIView()
view.backgroundColor = .red
view.layer.masksToBounds = true
return view
}()
var maskView: UIView = {
let view = UIView()
view.backgroundColor = .blue
return view
}()
}
This is the result I am expecting: (done in Photoshop)
As there is no magic way to mask the way in iOS, I present here a simple way to achieve this.
Don't forget to pan the clear area, If leaving the red square, it will become a blue square.
It's not hard to modify the subclass of UIViews for your own purpose, especially views.
import UIKit
class TestController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = .gray
view.addSubview(viewA)
view.addSubview(maskView)
maskView.maskedView = viewA
viewA.activeMask = maskView
viewA.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
viewA.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
viewA.widthAnchor.constraint(equalToConstant: 100).isActive = true
viewA.heightAnchor.constraint(equalToConstant: 100).isActive = true
viewA.translatesAutoresizingMaskIntoConstraints = false
maskView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 50).isActive = true
maskView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -50).isActive = true
maskView.widthAnchor.constraint(equalToConstant: 100).isActive = true
maskView.heightAnchor.constraint(equalToConstant: 100).isActive = true
maskView.translatesAutoresizingMaskIntoConstraints = false
}
var viewA: MyUIView = {
let view = MyUIView()
view.backgroundColor = .clear
view.layer.masksToBounds = true
return view
}()
var maskView: ActiveMaskView = {
let view = ActiveMaskView()
view.backgroundColor = .clear
return view
}()
}
class ActiveMaskView: UIView{
override func didMoveToSuperview() {
super.didMoveToSuperview()
let panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(moveAround(_:)))
self.addGestureRecognizer(panGesture)
}
weak var maskedView : UIView?
private var frameOrigin : CGPoint = CGPoint.zero
#objc func moveAround(_ panGesture: UIPanGestureRecognizer){
guard let superview = superview else {return}
switch panGesture.state {
case .began:
frameOrigin = frame.origin
self.backgroundColor = UIColor.blue
case .changed:
let translation = panGesture.translation(in: superview)
frame = CGRect.init(origin: CGPoint.init(x: frameOrigin.x + translation.x, y: frameOrigin.y + translation.y), size: frame.size)
maskedView?.setNeedsDisplay()
break
case .ended:
self.backgroundColor =
frame.intersects(maskedView!.frame) ?
UIColor.clear : UIColor.blue
maskedView?.setNeedsDisplay()
case .cancelled:
frame = CGRect.init(origin: frameOrigin , size: frame.size)
self.backgroundColor =
frame.intersects(maskedView!.frame) ?
UIColor.clear : UIColor.blue
maskedView?.setNeedsDisplay()
default:
break;
}
}
}
class MyUIView: UIView{
weak var activeMask: ActiveMaskView?
override func draw(_ rect: CGRect) {
super.draw(rect)
let ctx = UIGraphicsGetCurrentContext()
ctx?.setFillColor(UIColor.red.cgColor)
ctx?.fill(self.layer.bounds)
ctx?.setBlendMode(.sourceOut)
guard let activeMask = activeMask , let superview = superview else {
return
}
let sc = frame.intersection(activeMask.frame)
let interSection = superview.convert(sc, to: self)
ctx?.fill(interSection )
}
}

Swift: How to resize the font size within a UITextView while using AutoLayout?

I am one week into Swift programing and I want to build my first Application with Autolayout.
The current state of my app is that I generate a bunch of PictureCell in my ViewController. Their size is based on a slider value (and also calculated in the ViewController). This works just fine.
My struggle is customizing the inside of my PictureCell. My goal is to have a Label in the cell which font size is automatically resized when I resize the cell.
At the current state I can resize the Cell and the UITextView like I want, but I cannot resize the font within the Textview because it's constant is just called when it is initialized (I guess).
How can I address this problem in a good way?
Due to a not understanding of Swifts logic I have to post the whole code of the PictureCell:
class PictureCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
self.layer.cornerRadius = self.bounds.width / 20
self.clipsToBounds = true
setupViews()
}
let descriptionTextView: UITextView = {
let textView = UITextView()
textView.text = "Header"
textView.textColor = .black
textView.backgroundColor = .white
textView.translatesAutoresizingMaskIntoConstraints = false
textView.textAlignment = .center
textView.isEditable = false
textView.isScrollEnabled = false
textView.sizeToFit()
textView.font = UIFont.boldSystemFont(ofSize: textView.contentSize.height / 2) // Resize that
textView.layer.borderWidth = 2
textView.layer.borderColor = UIColor.red.cgColor
return textView
}()
var mainPicture: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageView.clipsToBounds = true
return imageView
}()
func setPictureForIndex(index: Int) {
self.mainPicture.image = UIImage(named: "color\(index)")
}
func setupViews() {
addSubview(mainPicture)
confMainPicture()
addSubview(descriptionTextView)
confDescriptionTextView()
}
func confMainPicture() {
mainPicture.translatesAutoresizingMaskIntoConstraints = false
mainPicture.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
mainPicture.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
mainPicture.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
mainPicture.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}
func confDescriptionTextView(){
descriptionTextView.translatesAutoresizingMaskIntoConstraints = false
descriptionTextView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
descriptionTextView.heightAnchor.constraint(equalTo: mainPicture.heightAnchor, multiplier: 0.25).isActive = true
descriptionTextView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
}
Too small for the text
Just fine
Too big to look good
This Code solved my problem more or less:
It doesn't work properly if the Cell is really small but it's better than the starting point and maybe someone can use it.
class PictureCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
self.translatesAutoresizingMaskIntoConstraints = false
self.layer.cornerRadius = self.bounds.width / 20
self.clipsToBounds = true
setupViews()
}
//MARK: -
var cellIdetifier = Int()
var mainPicture: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageView.clipsToBounds = true
imageView.layer.cornerRadius = imageView.bounds.width / 20
return imageView
}()
var descriptionBox: UIView = {
let descVie = UIView()
descVie.backgroundColor = UIColor(red: 0.1 , green: 0.1, blue: 0.1, alpha: 0.5)
descVie.layer.borderWidth = 0.5
descVie.layer.borderColor = UIColor.black.cgColor
descVie.clipsToBounds = true
descVie.layer.cornerRadius = descVie.bounds.height / 5
return descVie
}()
lazy var descLabel: UITextField = {
let label = UITextField()
label.textColor = .white
label.textAlignment = .center
label.clipsToBounds = true
label.font = UIFont.systemFont(ofSize: 15)
label.adjustsFontSizeToFitWidth = true
label.autoresizingMask = [.flexibleWidth,.flexibleHeight]
label.sizeToFit()
label.layoutIfNeeded()
label.isUserInteractionEnabled = false
return label
}()
func setPictureForIndex(index: Int, name: String) {
self.descLabel.text = name
self.mainPicture.image = UIImage(named: "color\(index)")
}
// MARK: -
// MARK: Layout
func setupViews() {
addSubview(mainPicture)
addSubview(descriptionBox)
descriptionBox.addSubview(descLabel)
confBounds()
}
func confBounds() {
mainPicture.translatesAutoresizingMaskIntoConstraints = false
mainPicture.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
mainPicture.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
mainPicture.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
mainPicture.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
descriptionBox.translatesAutoresizingMaskIntoConstraints = false
descriptionBox.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
descriptionBox.heightAnchor.constraint(equalTo: mainPicture.heightAnchor, multiplier: 0.25).isActive = true
descriptionBox.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
descriptionBox.bottomAnchor.constraint(greaterThanOrEqualTo: mainPicture.topAnchor, constant: 1)
descLabel.translatesAutoresizingMaskIntoConstraints = false
descLabel.widthAnchor.constraint(equalTo: descriptionBox.widthAnchor).isActive = true
descLabel.heightAnchor.constraint(equalTo: descriptionBox.heightAnchor).isActive = true
descLabel.bottomAnchor.constraint(equalTo: descriptionBox.bottomAnchor).isActive = true
descLabel.heightAnchor.constraint(equalTo: descriptionBox.heightAnchor).isActive = true
}
}

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