Mike
Mike

Reputation: 53

Make Image in rounded ImageView fit

I have a collectionviewCell with a rounded imageview which shows an icon. Unfortunately the icons are too big. How can I fit them to fit into the rounded ImageView:

Code

func makeItCircle() {

    self.imageView.layer.cornerRadius  = self.imageView.frame.height/2
    self.imageView.layer.masksToBounds = false
    self.imageView.clipsToBounds = true
    self.imageView.contentMode = .scaleAspectFit
}

Picture enter image description here

Upvotes: 2

Views: 437

Answers (2)

Kathan Lunagariya
Kathan Lunagariya

Reputation: 1

(100x100)

class CenterTab:UIView{

let container:UIView = {
   
    let v = UIView()
    v.backgroundColor = .white
    v.layer.cornerRadius = 100/2
    
    v.layer.shadowColor = UIColor.systemPurple.cgColor
    v.layer.shadowOpacity = 0.4
    v.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
    v.layer.shadowRadius = 7
    
    v.translatesAutoresizingMaskIntoConstraints = false
    return v
}()

let tabImg:UIImageView = {
   
    let img = UIImageView()
    img.contentMode = .scaleAspectFit
    img.clipsToBounds = true
    img.tintColor = .systemPurple
    img.translatesAutoresizingMaskIntoConstraints = false
    return img
}()


override init(frame: CGRect) {
    super.init(frame: frame)
    self.translatesAutoresizingMaskIntoConstraints = false
    
    container.addSubview(tabImg)
    self.addSubview(container)
}


override func layoutSubviews() {
    super.layoutSubviews()
    
    NSLayoutConstraint.activate([
        container.topAnchor.constraint(equalTo: self.topAnchor),
        container.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        container.trailingAnchor.constraint(equalTo: self.trailingAnchor),
        container.bottomAnchor.constraint(equalTo: self.bottomAnchor),
        
        tabImg.centerXAnchor.constraint(equalTo: container.centerXAnchor),
        tabImg.centerYAnchor.constraint(equalTo: container.centerYAnchor),
        tabImg.widthAnchor.constraint(equalTo: container.widthAnchor, multiplier: 0.60),
        tabImg.heightAnchor.constraint(equalTo: container.widthAnchor)
    ])
}


required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}}  

Upvotes: 0

dr_barto
dr_barto

Reputation: 6075

You can wrap the image views inside container views (the cell views you already have should work) to add some padding: center the image view inside its container and constraint its width and height to about 0.75 of the container. Also you'll have to set the background and corner rounding on the container, not on the image view.

Upvotes: 1

Related Questions