imageswiftuishapescornerradius

Add a circular image view with corner radius for an image in swiftUI


How can I add a circular view similar to the attachment below. In the attachment, the check is the image icon and I want to add the green background color in circular shape. I have a solution in Swift but, couldn't implement the same in swiftUI.

Related posts to my question: Add a border with cornerRadius to an Image in SwiftUI Xcode beta 5. But, this doesn't solve my issue.

Swift code to this implemention:

var imageView = UIImageView()
override init(theme: Theme) {
    super.init(theme: theme)
    imageView.clipsToBounds = true
    setLayout()
  }

override func layoutSubviews() {
    super.layoutSubviews()
    let cornerRadius = frame.height / 2
    imageView.setCornerRadius(cornerRadius)
    setCornerRadius(cornerRadius)
  }

CheckImage


Solution

  • This is not the simplest thing to come up with. Use this struct as a separate view. It will return the image properly sized on the circle.

    struct ImageOnCircle: View {
        
        let icon: String
        let radius: CGFloat
        let circleColor: Color
        let imageColor: Color // Remove this for an image in your assets folder.
        var squareSide: CGFloat {
            2.0.squareRoot() * radius
        }
        
        var body: some View {
            ZStack {
                Circle()
                    .fill(circleColor)
                    .frame(width: radius * 2, height: radius * 2)
                
                // Use this implementation for an SF Symbol
                Image(systemName: icon)
                    .resizable()
                    .aspectRatio(1.0, contentMode: .fit)
                    .frame(width: squareSide, height: squareSide)
                    .foregroundColor(imageColor)
                
                // Use this implementation for an image in your assets folder.
    //            Image(icon)
    //                .resizable()
    //                .aspectRatio(1.0, contentMode: .fit)
    //                .frame(width: squareSide, height: squareSide)
            }
        }
    }