【问题标题】:How can I place an asset image at given screen coordinates in SwiftUI?如何在 SwiftUI 中将资产图像放置在给定的屏幕坐标处?
【发布时间】:2021-08-19 05:24:30
【问题描述】:

我最近开始使用 XCode,为了练习,我使用 UIKit 开发了一个简单的游戏(没有意识到它正在被 SwiftUI 取代)。其核心是在屏幕矩形区域的随机位置显示多达 300 个小图像(随着游戏的进行而变化)。

为了放置每张图片,我使用了 imageView imageView = UIImageView(image: myImage)imageView.frame = CGRect(with calculated x, y, width and height values) 最后使它在视图中显示为view.addSubview(imageView)

谁能指出我正确的方向来为 SwiftUI 翻译这个。我做了很多搜索,但找不到任何直接有帮助的东西。 我唯一发现的是使用UIViewRepresentable 包装UIImageView class 的概念。这是要走的路吗? 如果是这样,我会怎么做?

感谢您的帮助:)

【问题讨论】:

    标签: ios image swiftui


    【解决方案1】:

    您可以使用一个充满图像的ZStack,每个图像都有一个随机的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)
                        )
                }
            }
        }
    }
    

    结果:

    【讨论】:

      猜你喜欢
      • 2019-07-10
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 2016-11-11
      • 1970-01-01
      相关资源
      最近更新 更多