微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在SwiftUI中将图片宽度设为其容器宽度的100%?

如何解决如何在SwiftUI中将图片宽度设为其容器宽度的100%?

我有用户从他们的移动设备上载图像,这些图像可以是纵向或横向。我将这些图像平铺成类似于Instagram帖子。我遇到的最大问题是肖像图像无法以容器宽度的100%渲染。真的很奇怪。

以下是我拍摄的“人像”照片的示例,并使用以下代码将其可视化:

vstack{
    AnimatedImage(url: URL(string: self.mediaLink))
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: UIScreen.main.bounds.width - 40)
}
.padding(.horizontal,20)
.frame(width: UIScreen.main.bounds.width - 40)

即使我指定了宽度,它仍然呈现不正确。它应该是UIScreen.main.bounds.width - 40,与其父vstack的宽度相同

enter image description here

使用GeometryReader时,我的代码如下:

GeometryReader{geo in
    vstack{
        AnimatedImage(url: URL(string: self.mediaLink))
            .resizable()
            .aspectRatio(contentMode: .fit)
            .frame(width: geo.size.width)
    }
}
.frame(width: UIScreen.main.bounds.width)

一个更糟!

enter image description here

感谢您的帮助!对宽高比使用.fill会使图像太大,并且会阻塞卡中的所有内容。以下代码未使用GeometryReader

vstack{
    AnimatedImage(url: URL(string: self.mediaLink))
        .resizable()
        .aspectRatio(contentMode: .fill)
        .frame(width: UIScreen.main.bounds.width - 40)
}
.frame(width: UIScreen.main.bounds.width - 40)

enter image description here

解决方法

我认为此更改将为您提供帮助:

VStack {
    AnimatedImage(url: URL(string: self.mediaLink))
       .resizable()
       .scaledToFit()
}
.frame(width: UIScreen.main.bounds.width - 40)
,

尝试使用function power(x,n) { let sum =1 for(let i =0;i<n;i++){ sum*=x } return sum } console.log(power(11,3))scaledToFill修饰符

clipped
,

仅使用Image(“ some_image”)测试了您的代码,如下所示,它可以工作(Xcode 12 / iOS 14),因此问题出在AnimatedImage或其他代码中。

VStack{
    Image("some_image")
        .resizable()
        .aspectRatio(contentMode: .fit)
        .frame(width: UIScreen.main.bounds.width - 40)
}
.padding(.horizontal,20)
.frame(width: UIScreen.main.bounds.width - 40)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。