Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oalansari82/1257a40ce9444c76969d45c0861e2f58 to your computer and use it in GitHub Desktop.
Save oalansari82/1257a40ce9444c76969d45c0861e2f58 to your computer and use it in GitHub Desktop.
ViewModifier for resizing images in SwiftUI. Resize an image to any size (square, circle, rectangle) while maintaining its aspect ratio.
import SwiftUI
/// Common aspect ratios
public enum AspectRatio: CGFloat {
case square = 1
case threeToFour = 0.75
case fourToThree = 1.75
}
/// Fit an image to a certain aspect ratio while maintaining its aspect ratio
public struct FitToAspectRatio: ViewModifier {
private let aspectRatio: CGFloat
public init(_ aspectRatio: CGFloat) {
self.aspectRatio = aspectRatio
}
public init(_ aspectRatio: AspectRatio) {
self.aspectRatio = aspectRatio.rawValue
}
public func body(content: Content) -> some View {
ZStack {
Rectangle()
.fill(Color(.clear))
.aspectRatio(aspectRatio, contentMode: .fit)
content
.scaledToFill()
.layoutPriority(-1)
}
.clipped()
}
}
// Image extension that composes with the `.resizable()` modifier
public extension Image {
func fitToAspectRatio(_ aspectRatio: CGFloat) -> some View {
self.resizable().modifier(FitToAspectRatio(aspectRatio))
}
func fitToAspectRatio(_ aspectRatio: AspectRatio) -> some View {
self.resizable().modifier(FitToAspectRatio(aspectRatio))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment