iOS: frame.size.width/2 doesn't produce a circle on every device

后端 未结 6 1416
长发绾君心
长发绾君心 2020-11-29 06:09

I\'m aware that the formulae frame.size.width/2 should produce a circle border, however in XCode I am currently experiencing some discrepancies.

I have

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 06:36

    You can create an extension to apply the mask and border straight to your image so it will always work disregarding the screen size / scale:

    edit/update:

    Xcode 11 • Swift 5 or later

    extension UIImage {
        var circleMask: UIImage? {
            let square = CGSize(width: min(size.width, size.height), height: min(size.width, size.height))
            let imageView = UIImageView(frame: .init(origin: .init(x: 0, y: 0), size: square))
            imageView.contentMode = .scaleAspectFill
            imageView.image = self
            imageView.layer.cornerRadius = square.width/2
            imageView.layer.borderColor = UIColor.white.cgColor
            imageView.layer.borderWidth = 5
            imageView.layer.masksToBounds = true
            UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
            defer { UIGraphicsEndImageContext() }
            guard let context = UIGraphicsGetCurrentContext() else { return nil }
            imageView.layer.render(in: context)
            return UIGraphicsGetImageFromCurrentImageContext()
        }
    }
    

    imgAvatar.image = yourImage.circleMask
    

提交回复
热议问题