SwiftUI:如何限制图像大小? [英] SwiftUI: How to constrain image size?

查看:49
本文介绍了SwiftUI:如何限制图像大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将图像大小限制在最小值和最大值之间.但是视图将宽度和高度都扩展到最大值,删除了原始纵横比.

I am trying to constrain image size between min and max. But the view expands both width and height to their max values, removing the original aspect ratio.

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()
    }
}

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

In the screenshot below, I want the red box to shrink to yellow box.

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

Tried using GeometryReader, but that gives the opposite effect of expanding the yellow box to red box.

有什么想法吗?

推荐答案

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

Here is a demo of possible approach - using view preferences and a bit different layout order (we give area to fit image with aspect and then by resulting image size constrain this area).

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

Demo prepared & tested with 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)
    }
}

这篇关于SwiftUI:如何限制图像大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆