Forked from karigrooms/swiftui-resize-image-and-maintain-aspect-ratio.swift
Created
July 9, 2021 15:23
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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