如何在 SwiftUI 中垂直显示旋转图像数组?

问题描述 投票:0回答:1

我的应用程序有一个具有属性

hand
的结构数组
let blatt: Image
。在
init
期间,将
Image
分配给此属性。

要水平显示这样的数组,我使用以下代码(

scaledWidth
是一些常量):

HStack(spacing: 10) {
    ForEach((0 ..< hand.count), id: \.self) {
        hand[$0].blatt
            .resizable()
            .scaledToFit() 
            .frame(height: scaledWidth)
            .border(.black)
    }
}

这给出了以下输出:

这正是我所期望的。

另一个数组要垂直显示。为此,我使用以下代码:

VStack(spacing: 10) {
    ForEach((0 ..< hand.count), id: \.self) {
        hand[$0].blatt
            .resizable()
            .scaledToFit() 
            .rotationEffect(Angle(degrees: 90))
            .frame(width: scaledWidth, height: scaledWidth)
            .border(.black)
    }
}

这还给出了以下输出:

这里,每帧的高度(如边框所示)是未旋转图像的高度。

由于我知道图像的长宽比

aspectRatioBlatt
,我可以使用
.frame(width: scaledWidth, height: scaledWidth / aspectRatioBlatt)
调整输出。然后,框架具有正确的尺寸和正确的间距,但里面的图像太少了。同样,框架的高度等于内部未旋转图像的高度。

我尝试了很多视图修改器和多种组合,但都失败了。我什至尝试使用自定义布局,如此处建议的垂直文本,但这也不起作用。 当然,我可以使用第二组翻转图像,但在 SwiftUI 中没有它应该是可能的。
怎样做才是正确的?

ios swiftui foreach image-rotation
1个回答
0
投票
HStack

可能是最简单的方法。

但除此之外,请尝试使用 

scaledToFill

而不是

scaledToFit
作为旋转版本:
struct ContentView: View {

    let scaledWidth = CGFloat(50)
    let colors: [Color] = [.green, .blue, .mint, .teal, .purple]

    var body: some View {
        VStack(spacing: 50) {
            HStack(spacing: 10) {
                ForEach((0 ..< colors.count), id: \.self) { index in
                    Image(systemName: "figure.wave")
                        .resizable()
                        .scaledToFit()
                        .frame(width: scaledWidth)
                        .background { colors[index] }
                        .border(.black)
                }
            }
            VStack(spacing: 10) {
                ForEach((0 ..< colors.count), id: \.self) { index in
                    Image(systemName: "figure.wave")
                        .resizable()
                        .scaledToFill()
                        .frame(width: scaledWidth)
                        .background { colors[index] }
                        .border(.black)
                        .rotationEffect(.degrees(90))
                        .frame(height: scaledWidth)
                }
            }
        }
    }
}

RotatedImages

© www.soinside.com 2019 - 2024. All rights reserved.