How to set image in circle in swift

2019-03-07 21:21发布

How can i make i circle picture with swift ?

My ViewController :

import UIKit
import Foundation

class FriendsViewController : UIViewController{

    @IBOutlet weak var profilPicture: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        profilPicture = UIImageView(frame: CGRectMake(0, 0, 100, 100))
    }
}

My profilPicture = UIImageView(frame: CGRectMake(0, 0, 100, 100)) do nothing ..

Exemple: http://www.appcoda.com/ios-programming-circular-image-calayer/

12条回答
We Are One
2楼-- · 2019-03-07 21:24

You can simple create extension:

import UIKit

extension UIImageView {

   func setRounded() {
      let radius = CGRectGetWidth(self.frame) / 2
      self.layer.cornerRadius = radius
      self.layer.masksToBounds = true
   }
}

and use it as below:

imageView.setRounded()
查看更多
孤傲高冷的网名
3楼-- · 2019-03-07 21:26

Don't know if this helps anyone but I was struggling with this problem for awhile, none of the answers online helped me. For me the problem was I had different heights and widths set on the image in storyboard. I tried every solution on stack and it turns out it was something as simple as that. Once I set them both to 200 my circle profile image was perfect. This was code then in my VC.

profileImage2.layer.cornerRadius = profileImage2.frame.size.width/2
    profileImage2.clipsToBounds = true
查看更多
三岁会撩人
4楼-- · 2019-03-07 21:27

If you mean you want to make a UIImageView circular in Swift you can just use this code:

imageView.layer.cornerRadius = imageView.frame.height / 2
imageView.clipsToBounds = true
查看更多
Viruses.
5楼-- · 2019-03-07 21:28
import UIKit

class ViewController: UIViewController {
  @IBOutlet weak var image: UIImageView!

  override func viewDidLoad() {
    super.viewDidLoad()

    image.layer.borderWidth = 1
    image.layer.masksToBounds = false
    image.layer.borderColor = UIColor.black.cgColor
    image.layer.cornerRadius = image.frame.height/2
    image.clipsToBounds = true
}

That is all you need....

查看更多
手持菜刀,她持情操
6楼-- · 2019-03-07 21:29

Download and use Toucan from GitHub. It's offered in Swift. Mind numbingly easy. It also offers a bunch of other image effects.

查看更多
Fickle 薄情
7楼-- · 2019-03-07 21:30

For Swift3/Swift4 Developers:

let radius = yourImageView.frame.width / 2
yourImageView.layer.cornerRadius = radius
yourImageView.layer.masksToBounds = true
查看更多
登录 后发表回答