UIImageview not getting rounded - ios

I am trying to create a circular image and I have implemeted the right code but I do not know why it does not get rounded below is my code
lazy var profileImage: UIImageView = {
let image = UIImageView()
image.translatesAutoresizingMaskIntoConstraints = false
image.layer.borderColor = UIColor.blue.cgColor
image.layer.borderWidth = 1.5
image.image = UIImage(named: "prof.jpg")
image.contentMode = .scaleAspectFit
image.layer.cornerRadius = image.frame.size.width / 2
image.clipsToBounds = true
return image
}()
and my constraints are
fileprivate func layout() {
view.addSubview(profileImage)
NSLayoutConstraint.activate([
profileImage.centerXAnchor.constraint(equalTo: view.centerXAnchor),
profileImage.centerYAnchor.constraint(equalTo: view.centerYAnchor),
profileImage.heightAnchor.constraint(equalToConstant: 200),
profileImage.widthAnchor.constraint(equalToConstant: 200),
])
}
layout() is then added to viewDidLoad

You’re not giving your UIImageView a frame when it’s initialised so it uses .zero as a default. This means that when you access image.frame.size.width you are getting a value of 0.
What I would suggest is to move your image.layer.cornerRadius = image.frame.size.width / 2 into the viewDidLayoutSubviews override on your UIViewController class.
You could also create a custom class that subclasses UIImageView and implements the same logic. The override for UIImageView would be layoutSubviews.

Image doesn't have a frame *image.layer.cornerRadius = image.frame.size.width / 2* inside the closure.
So set the corner radius after the profileImage is set with its constraints
profileImage.layoutIfNeeded()
profileImage.layer.cornerRadius = profileImage.frame.size.width / 2

Related

UIImageView and vector images: how to adjust for zooming to avoid blurry image

I have a vector image named Link in my asset catalog (in my case contained in a pdf, setup as preserve vector data) and I use an UIImageView to show this image in my view hierarchy:
let image = UIImage(named: "Link")
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.image = image
And this is the simple view hierarchy:
As you can see I use .scaleAspectFit and when I set a frame for imageView the UIImageView renders the image in the desired resolution to look sharp on screen. So far so good.
In order to zoom an scroll I use an UIScrollView. After zooming in the image in the imageView appears blurry due to obviously having too low resolution for the higher zoom:
Is there any straight forward way to adjust UIImageView so that it renders the image in a higher resolution?
Discussion:
Using .scaleAspectFit the renderered image resolution resolution seems to depend on the frame set for imageView. So setting a bigger frame and scaling the view using its transform property works, but is also rather tedious.
Another way is manually rendering the image at an apporpriate solution from the vector image using UIGraphicsImageRenderer or similar. This is currenlty my preferred solution, but I am wondering if there is an easier way using UIImageView.
Here is sample code (just replace your main ViewController with this in a new project), which shows the blurry image when zooming in (just use any vector image named Link in your assets and choose render as "Template Image"):
class ViewController: UIViewController, UIScrollViewDelegate {
let contentView: UIView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 1000.0, height: 1000.0))
let scrollView: UIScrollView = {
let view = UIScrollView(frame: CGRect(x: 0.0, y: 0.0, width: 400.0, height: 400.0))
view.minimumZoomScale = 0.5
view.maximumZoomScale = 10.0
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.delegate = self
self.contentView.backgroundColor = UIColor.green.withAlphaComponent(0.2)
// setup view hierarchy
self.scrollView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(self.scrollView)
self.scrollView.addSubview(self.contentView)
// constraints
self.scrollView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.scrollView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
self.scrollView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.contentView.leftAnchor.constraint(equalTo: self.scrollView.leftAnchor).isActive = true
self.contentView.rightAnchor.constraint(equalTo: self.scrollView.rightAnchor).isActive = true
self.contentView.topAnchor.constraint(equalTo: self.scrollView.topAnchor).isActive = true
self.contentView.bottomAnchor.constraint(equalTo: self.scrollView.bottomAnchor).isActive = true
self.contentView.widthAnchor.constraint(equalToConstant: 10.0 * self.view.frame.width).isActive = true
self.contentView.heightAnchor.constraint(equalToConstant: 10.0 * self.view.frame.height).isActive = true
// setup imageView
let image = UIImage(named: "Link")
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.image = image
imageView.tintColor = UIColor.black
imageView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(imageView)
// add constraints
imageView.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor).isActive = true
imageView.widthAnchor.constraint(equalToConstant: 100.0).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 100.0).isActive = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let zoomScale = 8.0
self.scrollView.contentOffset = CGPoint(x: 0.5 * (self.contentView.frame.width - self.scrollView.frame.width), y: 0.5 * (self.contentView.frame.height - self.scrollView.frame.height))
self.scrollView.zoomScale = zoomScale
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.contentView
}
}

Shadow is not visible on some UI elements

I have a helper method that helps me to add a shadow on all UI elements, and it works perfectly for the most of them, but on some of them, it doesn't.
For example, on this stackView below, there is no shadow when I run my app:
var container = UIStackView()
let stackView = UIStackView(arrangedSubviews: [button1, button2, button3])
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.alignment = .fill
container = stackView
self.view.addSubview(container)
container.snp.makeConstraints { make in
make.top.equalTo(view).offset(25)
make.right.equalTo(view).offset(-25)
make.width.equalTo(view.frame.width * 0.185)
make.height.equalTo(view.frame.width * 0.65)
}
container.layer.addShadow()
I have also tried to call this addShadow() for my buttons(button1, button2, button3), but didn't work.
I have tried different values in parameters of addShadow(), but...
Another example is where it WORKS, on my imageView:
let avatarImageView = UIImageView()
self.addSubview(avatarImageView)
avatarImageView.contentMode = .scaleAspectFit
avatarImageView.image = UIImage(named: imageName)
avatarImageView.snp.makeConstraints { (make) in
make.height.equalToSuperview()
make.width.equalToSuperview().multipliedBy(0.5)
make.left.equalToSuperview()
}
avatarImageView.layer.addShadow(opacity: 0.3, offsetWidth: 13, offsetHeight: 8)
Here is a shadow method(in extension of CALayer):
func addShadow(scale: Bool = true, opacity: Float = 0.4, offsetWidth: Int = 5, offsetHeight: Int = 5, radius: CGFloat = 5) {
masksToBounds = false
shadowColor = UIColor.black.cgColor
shadowOpacity = opacity
shadowOffset = CGSize(width: offsetWidth, height: offsetHeight)
shadowRadius = radius
shouldRasterize = true
rasterizationScale = scale ? UIScreen.main.scale : 1
}
See Apple's UIStackView documentation.
Managing the Stack View’s Appearance:
The UIStackView is a nonrendering subclass of UIView.
UIStackView just manages the position and size of its arranged views, background or shadow won't show.

How to scroll images horizontally in iOS swift

I have an imageview called "cardImgView" in that I want to load two images by scrolling horizontally, I have tried the following way, in this case I can able to scroll only to up and down and the images also not changing, anyone
have idea how to do this correctly.
let img: UIImage = self.dataDict.object(forKey: kCardImgFront) as! UIImage
let img2:UIImage = self.dataDict.object(forKey: kCardImgBack) as! UIImage
imgArray = [img, img2]
for i in 0..<imgArray.count{
cardImgView?.image = imgArray[i]
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
scrollView.addSubview(cardImgView!)
}
thanks in advance.
First, as I commented, you are currently using a single UIImageView --- so each time through your for-loop you are just replacing the .image of that one image view.
Second, you will be much better off using auto-layout and constraints, instead of trying to explicitly set frames and the scrollView's contentSize.
Third, UIStackView is ideal for your use case - adding multiple images that you want to horizontally scroll.
So, the general idea is:
add a scroll view
add a stack view to the scroll view
use constraints to make the stack view control the scroll view's contentSize
create a new UIImageView for each image
add each image view to the stack view
Here is a simple example that you can run in a Playground page to see how it works. If you add your own images named image1.png and image2.png to the playground's resources, they will be used (otherwise, this example creates solid blue and solid green images):
import UIKit
import PlaygroundSupport
// UIImage extension to create a new, solid-color image
public extension UIImage {
public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
let rect = CGRect(origin: .zero, size: size)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
}
class TestViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create a UIScrollView
let scrollView = UIScrollView()
// we will set the auto-layout constraints
scrollView.translatesAutoresizingMaskIntoConstraints = false
// set background color so we can see the scrollView when the images are scrolled
scrollView.backgroundColor = .orange
// add the scrollView to the view
view.addSubview(scrollView)
// pin scrollView 20-pts from top/bottom/leading/trailing
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0).isActive = true
scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20.0).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20.0).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20.0).isActive = true
// create an array of empty images in case this is run without
// valid images in the resources
var imgArray = [UIImage(color: .blue), UIImage(color: .green)]
// if these images exist, load them and replace the blank images in imgArray
if let img1: UIImage = UIImage(named: "image1"),
let img2: UIImage = UIImage(named: "image2") {
imgArray = [img1, img2]
}
// create a UIStackView
let stackView = UIStackView()
// we can use the default stackView properties
// but can change axis, alignment, distribution, spacing, etc if desired
// we will set the auto-layout constraints
stackView.translatesAutoresizingMaskIntoConstraints = false
// add the stackView to the scrollView
scrollView.addSubview(stackView)
// with auto-layout, scroll views use the content's constraints to
// determine the contentSize,
// so pin the stackView to top/bottom/leading/trailing of the scrollView
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 0.0).isActive = true
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0.0).isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: 0.0).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0.0).isActive = true
// loop through the images
for img in imgArray {
// create a new UIImageView
let imgView = UIImageView(image: img)
// we will set the auto-layout constraints, and allow the stackView
// to handle the placement
imgView.translatesAutoresizingMaskIntoConstraints = false
// set image scaling as desired
imgView.contentMode = .scaleToFill
// add the image view to the stackView
stackView.addArrangedSubview(imgView)
// set imgView's width and height to the scrollView's width and height
imgView.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 1.0).isActive = true
imgView.heightAnchor.constraint(equalTo: scrollView.heightAnchor, multiplier: 1.0).isActive = true
}
}
}
let vc = TestViewController()
vc.view.backgroundColor = .red
PlaygroundPage.current.liveView = vc
I modified my code and tried as follows and its working now. with page contrlller
let imgArray = [UIImage]()
let img: UIImage = self.dataDict.object(forKey: kCardImgFront) as! UIImage
let img2:UIImage = self.dataDict.object(forKey: kCardImgBack) as! UIImage
imgArray = [img, img2]
for i in 0..<imgArray.count {
let imageView = UIImageView()
imageView.image = imgArray[i]
let xPosition = self.view.frame.width * CGFloat(i)
imageView.frame = CGRect(x: xPosition, y: 0, width:
self.scrollView.frame.width + 50, height: self.scrollView.frame.height)
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i + 1)
scrollView.addSubview(imageView)
}
self.scrollView.delegate = self
func scrollViewDidScroll(_ scrollView: UIScrollView){
pageController.currentPage = Int(self.scrollView.contentOffset.x /
CGFloat(4))
}
I think you need to set a proper frame for the cardImgView. It would be something like
cardImgView.frame = CGRect(x: scrollView.frame.width * CGFloat(i), y: 0, width: scrollView.frame.width, height: scrollView.frame.height)
Finally, after the for loop, you need to set scroll view's content size:
scrollView.contentSize.width = scrollView.frame.width * imgArray.count
Hope this helps.
I have written scrolling images horizontally in swift. Please check with this:
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
#IBOutlet weak var Bannerview: UIView!
var spinner = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
var loadingView: UIView = UIView()
var loadinglabel: UILabel = UILabel()
var nextPage :Int!
var titlelab :UILabel!
var bannerimg :UIImageView!
var scroll :UIScrollView!
var viewPanel :UIView!
var pgCtr:UIPageControl!
var bannerArr:[String]!
var imgUrlstr :NSString!
var screenSize: CGRect!
var screenWidth: CGFloat!
var screenHeight: CGFloat!
func uicolorFromHex(rgbValue:UInt32)->UIColor
{
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:1.0)
}
override func viewWillAppear(_ animated: Bool)
{
screenSize = UIScreen.main.bounds
screenWidth = screenSize.width
screenHeight = screenSize.height
bannerArr = ["image1.jpeg","image2.jpeg","image3.jpeg","images4.jpeg","images5.jpeg"]
self.bannerview()
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.navigationController?.navigationBar.isTranslucent = false
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
}

rounded imageView 's border is not smooth after setting image property

class PPAvatarCollectionCell: UICollectionViewCell {
var imageView:UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
imageView = UIImageView(frame: CGRect(origin: CGPointMake(0, 0), size: CGSizeMake(frame.size.width, frame.size.height)))
self.addSubview(imageView)
imageView.contentMode = .ScaleAspectFill
imageView.backgroundColor = UIColor.whiteColor()
imageView.layer.borderColor = UIColor.greenColor().CGColor
imageView.layer.borderWidth = 10
imageView.image = UIImage(named: "demo")
imageView.layer.cornerRadius = frame.size.width*0.5
imageView.clipsToBounds = true
}
the border is smooth and great with above code
but after add imageView.image = UIImage(named: "demo")
the imageView's border is no longer smooth.
Why did this happen ?
UPDATE:
Seems something wrong with layer.radius ,the border is smooth even with image property set on imageView after remove imageView.layer.cornerRadius = frame.size.width*0.5
UPDATE 2:
turn out to be something wrong with UICollectionViewCell , imageView is a part of UICollectionViewCell
u can use 2 imageview 1 to show image and second to hide and show circular image.
1st imageview show image as it is.
2nd imageview which will have white background and green circle above 1st image and middle of image will be transparent
Basically, your image should be a square. Than do these:
imageView.layer.cornerRadius = self.frame.height / 2
imageView.layer.masksToBounds = false
imageView.clipsToBounds = true
imageView.image = "yourSquareImage"
Check the full solution with easy using extension:
https://stackoverflow.com/a/36102901/2125010

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