0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftUIで純正写真アプリのようなサムネイル表示

Posted at

UIScreenやGeometoryReaderを使わずに1:1のサムネイル表示したくて、ちょっとハマったので共有

完成コード


    ScrollView {
        LazyVGrid(
            columns: Array(repeating: GridItem(.flexible(), spacing: 2), count: 3),
            spacing: 2
        ) {
            ForEach(images, id: \.self) { image in
                Rectangle()
                    .fill(.clear)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .aspectRatio(1, contentMode: .fit)
                    .overlay {
                        Image(uiImage: image)
                            .resizable()
                            .scaledToFill()
                    }
                    .clipped()
            }
        }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)

Imageのリサイズだけで頑張ろうとすると、UIScreenやGeometoryReaderを使わないと厳しい実装になってしまうと思います。
1:1の矩形領域を描画してそこに画像を満たしてClipするように作れば、frame情報を計算せずに実装できます。

scaledToFill()scaledToFitにすれば、純正写真アプリの様にアスペクト比グリッドに変更可能です

ググって出てきたImageのリサイズで頑張るやり方

これでも同じ挙動になりますが、minWidth:0 ,minHeight: 0の記述や、aspectRatioを2回書ける処理がシンプルじゃないので、採用しませんでした。

    Image(uiImage: image)
        .resizable()
        .aspectRatio(contentMode: .fill)
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
        .clipped()
        .aspectRatio(1, contentMode: .fit)
0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?