create a circular profile icon with image in swiftui in swift

You can create a circular profile icon with an image in SwiftUI by applying the .clipShape() modifier to an Image view and providing a Circle shape as the argument. Here's an example implementation:

main.swift
Image("profile_pic")
    .resizable()
    .frame(width: 100, height: 100)
    .clipShape(Circle())
99 chars
5 lines

In this code snippet, we start with an Image view that displays an image named "profile_pic". We then make the image resizable and set the frame to be 100 by 100 pixels. Finally, we clip the image to a Circle shape using the .clipShape() modifier.

You can adjust the size of the image by changing the frame dimensions or by using a GeometryReader to dynamically size the view based on the available space.

Note that if your image is not already a perfect square, it may be distorted when clipped into a circle. To avoid distortion, you can use a resizable Rectangle view as a container for the image and apply .aspectRatio(contentMode: .fit) to preserve the aspect ratio of the original image:

main.swift
Rectangle()
    .fill(Color.white)
    .aspectRatio(contentMode: .fit)
    .frame(width: 100, height: 100)
    .overlay(
        Image("profile_pic")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .clipShape(Circle())
    )
258 chars
11 lines

This implementation uses a Rectangle view as a container for the image instead of applying .frame() directly to the Image. The Rectangle is filled with white to provide a border around the circular image. The .aspectRatio(contentMode: .fit) modifier is applied to both the Rectangle and the Image to preserve the aspect ratio of the original image. Finally, the Image is clipped to a Circle shape as before.

gistlibby LogSnag