简体   繁体   中英

UIImageView on circular background, on a UICollectionViewCell

I want to give a circular coloured background to a UIImageView on a UICollectionViewCell . To do this I am applying a cornerRadius to the UIImageView 's layer .

Obviously the cornerRadius needs to be half the frame 's height/width. I'm putting this code in the layoutSubviews method, which is probably wrong, because when it's called the image's frame is huge. Rotating the phone and rotating it back solves the problem, because by then the frame has been correctly set.

Where should I be putting the cornerRadius calculation code?

Is there a better way of getting an image on a circular background anyway?

Note: The UIImageView may change height/width during layout operations. I'm using Autolayout.

Code:

class EventPickerCell: UICollectionViewCell
{
    @IBOutlet weak var image: UIImageView!
    @IBOutlet weak var label: UILabel!

    override func layoutSubviews()
    {
        super.layoutSubviews()

        print("imagesizes = frame = \(image.frame), bounds = \(image.bounds)")
        image.layer.cornerRadius = CGRectGetWidth(image.frame)/2
        image.layer.backgroundColor = UIColor.whiteColor().CGColor
    }
}

You provide the cells to the collection view controller in func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell . This is where you configure the cell, so you should update the image layer here too.

If you want just a view to do this by itself, you could create a UIImageView subclass and watch for bounds updates:

override var bounds: CGRect {
  didSet {
    // update layer here
  }
}

You could always just subclass a UIImageView in order to set the cornerRadius when the frame changes.

class CircularImageView : UIImageView {
    override var frame: CGRect {
        didSet { // frame did change
            self.layer.cornerRadius = frame.size.width*0.5 // set corner radius
        }
    }
}

Try cellForItemAtIndexPath.

You can instantiate your cell as EventPickerCell and have access to all its properties.

Another way would be to look into computed variables.

Something along those lines: Inside your cell:

var image: UIImage = UIImage() {
    didSet {
         imageView.image = image
         imageView.layer.cornerRadius = image.size.width
}

this will set the corner radius as soon as you set the cells image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM