set cornerRadius and setbackgroundimage to UIButton

后端 未结 7 1083

I am trying to set cornerRadius of UIButton but I dont know how to do it.

If I do like this:

button.layer.cornerRadius = 5;

works w

相关标签:
7条回答
  • 2020-12-23 20:17

    Using UIGraphicsImageRenderer, you can use the cgContext property of UIGraphicsImageRendererContext to access the CGContext and add a rounded path:

    UIGraphicsImageRenderer(size: size).image { context in
        let rect = CGRect(origin: .zero, size: size)
        let clipPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath
        context.cgContext.addPath(clipPath)
        context.cgContext.setFillColor(self.cgColor)
        context.cgContext.fillPath()
    }
    

    Added as an extension to UIColor:

    extension UIColor {
        public func image(_ size: CGSize = CGSize(width: 10, height: 10), cornerRadius: CGFloat = 4) -> UIImage {
            return UIGraphicsImageRenderer(size: size).image { context in
                let rect = CGRect(origin: .zero, size: size)
                let clipPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath
                context.cgContext.addPath(clipPath)
                context.cgContext.setFillColor(self.cgColor)
                context.cgContext.fillPath()
            }
        }
    }
    

    This approach will also allow you to add a shadow to the button unlike using clipsToBounds.

    0 讨论(0)
提交回复
热议问题