SwiftUI: ViewModifier where content is an Image

In this case where the modification is specific to a particular view type, Image say, you could just add an extension on that view type directly:

extension Image {
    func myImageModifier() -> some View {
        self
            .resizable()
            .aspectRatio(1.0, contentMode: .fit)
            .clipShape(Circle())
   }
}

A full playground text example follows. If you add a cute otter picture in your playground “Resources” folder named “Otter.png” you get a prettier result 🙂

import PlaygroundSupport
import SwiftUI

let image = (UIImage(named: "Otter.png") ?? UIImage(systemName: "exclamationmark.square")!)

struct ContentView: View {
    var body: some View {
        VStack {
            Text("hello world")
            Image(uiImage: image)
                .myImageModifier()
        }
    }
}

extension Image {
    func myImageModifier() -> some View {
        self
            .resizable()
            .aspectRatio(1.0, contentMode: .fit)
            .clipShape(Circle())
    }
}

PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView())

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)