Mark Highton Ridley
Mark Highton Ridley

Reputation: 136

How can I place an asset image at given screen coordinates in SwiftUI?

I recently started with XCode and for practice I deveoped a simple game usiing UIKit (not realizing it was being superceded by SwiftUI). At its core is the display of up to 300 small images (varies as the game progresses) at random locations in a rectangular area of the screen.

To place each image I used an imageView imageView = UIImageView(image: myImage) and an imageView.frame = CGRect(with calculated x, y, width and height values) and finally causing it to be displayed in the view with view.addSubview(imageView)

Can someone please point me in the right direction to translate this for SwiftUI. I've done lots of searching but can't find anything that helps directly. The only thing I have found is the concept of using UIViewRepresentable to wrap a UIImageView class. Is that the way to go? If so, how would I go about it?

Thanks for any help :)

Upvotes: 1

Views: 1524

Answers (1)

aheze
aheze

Reputation: 30318

You can use a ZStack that's filled with images, each of which have a random position.

struct ContentView: View {
    let screenWidth = UIScreen.main.bounds.width
    let screenHeight = UIScreen.main.bounds.height
    
    var body: some View {
        ZStack {
            ForEach(0..<300) { _ in
                Image(systemName: "plus")
                    .frame(width: 30, height: 30)
                    .background(Color.green)
                    .position( /// here!
                        x: CGFloat.random(in: 0..<screenWidth),
                        y:  CGFloat.random(in: 0..<screenHeight)
                    )
            }
        }
    }
}

Result:

Images placed randomly on screen

Upvotes: 3

Related Questions