簡體   English   中英

如何在 SwiftUI 的滾動視圖中水平和垂直居中圖像

[英]How to horizontally and vertically center an image inside a scrollview in SwiftUI

想象一個簡單的滾動視圖,其中包含一個帶有圖像的內容視圖,如果高度小於滾動視圖的高度,則該圖像應該垂直居中。

如果圖像超過滾動視圖的高度,則滾動視圖應允許滾動以顯示完整的圖像。

此外,如果圖像比它的容器窄,它應該水平居中

縮小圖像時,應始終保持其固有 aspectRatio

這些是要求

你會如何在 SwiftUI 中做到這一點?

這里需要解決哪些問題?

  • 滾動視圖的內容視圖不會自動居中,它們會在頂部對齊
  • 可調整大小的圖像總是占據它們獲得的所有空間,即使本質上小於其幀(因此它們會按比例放大,這很討厭)
  • 圖像的縱橫比需要保持原來的樣子
  • 如果圖像比滾動視圖本身高,則內容需要可滾動以顯示整個圖像

什么不應該是解決方案的一部分:

  • 捏成比例

Stackoverflow 上的類似問題(沒有真正解決問題):

一種建議的解決方案如下:

struct TestView: View {

    let image: UIImage

    var body: some View {
        GeometryReader { geo in
            ScrollView {
                SwiftUI.Group {
                    Image(uiImage: self.image)
                        // make image resizable to expand to frame's bounds
                        .resizable()
                        // make sure the aspect ratio when scaling is
                        // like the original image ratio
                        .aspectRatio(contentMode: .fit)
                        // limit the image's width to its intrinsic width
                        // this gets rid of **upscaling**
                        .frame(maxWidth: image.size.width)

                }
                // makes sure the container is always at least as tall as the scrollview
                // so that the **vertical alignment** works properly
                // additionally we let the frame expand horizontally to the edges of
                // the scrollview for horizontal centering to work                
                .frame(maxWidth: geo.size.width, minHeight: geo.size.height)
            }
        }
    }
}

添加了注釋來解釋每個命令的用途。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM