【问题标题】:SwiftUI: How to constrain image size?SwiftUI:如何限制图像大小?
【发布时间】:2020-09-14 03:56:27
【问题描述】:

我正在尝试将图像大小限制在最小和最大之间。但是视图将宽度和高度都扩展为最大值,移除了原来的纵横比。

import SwiftUI

struct ImageConstrainSizeTest: View {
    var body: some View {
        Image("bike")
            .resizable()
            .aspectRatio(contentMode: .fit)
            .border(Color.yellow, width: 5)
            .frame(minWidth: 10, maxWidth: 300, minHeight: 10, maxHeight: 300, alignment: .center)
            .border(Color.red, width: 5)
    }
}

struct ImageConstrainSizeTest_Previews: PreviewProvider {
    static var previews: some View {
        ImageConstrainSizeTest()
    }
}

在下面的截图中,我希望红色框缩小为黄色框。

尝试使用 GeometryReader,但这会产生将黄色框扩展到红色框的相反效果。

有什么想法吗?

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    这是一个可能的方法的演示 - 使用视图首选项和稍微不同的布局顺序(我们给区域以适应图像的纵横比,然后通过生成的图像大小限制该区域)。

    使用 Xcode 11.7 / iOS 13.7 准备和测试的演示

    struct ViewSizeKey: PreferenceKey {
        typealias Value = CGSize
        static var defaultValue: CGSize = .zero
        static func reduce(value: inout Value, nextValue: () -> Value) {
            value = nextValue()
        }
    }
    
    struct ImageConstrainSizeTest: View {
        @State private var size = CGSize.zero
        var body: some View {
            Color.clear
                .frame(width: 300, height: 300)
                .overlay(
                    Image("img")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .border(Color.yellow, width: 5)
                        .background(GeometryReader {
                            Color.clear.preference(key: ViewSizeKey.self,
                                value: $0.size) })
                )
                .onPreferenceChange(ViewSizeKey.self) {
                    self.size = $0
                }
                .frame(maxWidth: size.width, maxHeight: size.height)
                .border(Color.red, width: 5)
        }
    }
    

    【讨论】:

    • 谢谢!这很好用。我确实将内部 .background() 更改为 .overlay(),因为 .background 无法在图像上使用 .eraseToAnyView() 修饰符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-07
    • 2013-04-05
    • 2014-06-17
    • 2014-03-18
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    相关资源
    最近更新 更多