Language/Swift
SwiftUI AspectRatio / GeometryReader 이용하기
IFLA
2022. 11. 29. 10:12
AspectRatio
이미지를 원래 크기 그대로 넣고 싶은 경우도 있지만 사이즈 조정을 해서 지정된 사이즈 안에 이미지가 들어가게 하려면 AspectRatio 를 이용하면 원하는 크기에 이미지가 맞게 조정된다. .clipped() 를 이용해 이미지를 자를 수 있지만 .resizable() 과 .aspectRatio() 를 사용하면 간편하다.
기본 코드
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "star.circle")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 300, height: 300)
}
}
}
- .aspectRadio(contentMode: ) 옵션 : .fit, .fill
실행 화면
GeometryReader
이미지를 자동으로 확장할 때 사용한다. GeometryReader 는 자식 뷰에 부모 뷰와 기기에 대한 크기 및 좌표계 정보를 전달하는 기능을 수행하는 컨테이너 뷰다. 뷰의 크기가 변경되더라도 그 값이 자동으로 갱신된다.
기본 코드
// 좌측
ZStack{
Circle().fill(Color.yellow)
.frame(width: 350, height: 350)
Circle().fill(Color.green)
.frame(width: 280, height: 280)
Circle().fill(Color.blue)
.frame(width: 200, height: 200)
}
// 우측
GeometryReader { geo in
Circle().fill(Color.yellow)
.frame(width: 350, height: 350)
Circle().fill(Color.green)
.frame(width: 280, height: 280)
Circle().fill(Color.blue)
.frame(width: 200, height: 200)
}
- 크기를 지정하지 않으면, 주어진 공간 내에서 최대 크기를 가진다.
실행 화면
개발자 Document
Apple Developer Documentation
developer.apple.com
Apple Developer Documentation
developer.apple.com