I have a view
struct CustomImageView : View {
var body: some View {
Image("someImage")
}
}
when i reference this view outside, i cannot make the image resizable. I know i can pass parameters, but i was looking for a neater way to do this through modifiers?
VStack {
CustomImageView()
.resizable() // This does not work
}
resizable seems to only work with the image directly. Does anyone know how to make the CustomImageView resizable?
Update: I understand i can use a parameter, but is there anyway to do it using modifiers? Resizable was only one property, but there are other properties. And listing them all as indvidual variables will be too much
Implemented Answer based on @matteo-pacini It uses AlamofireImage to load a remote image in ImageView.
struct RemoteImage : View {
var url: URLConvertible
@ObjectBinding var imageLoader = AlamofireImageLoader()
private (set) var _resizable: (capInsets: EdgeInsets, resizingMode: Image.ResizingMode) = (EdgeInsets(), .stretch)
var body: some View {
Image(uiImage: imageLoader.image)
.resizable(capInsets: _resizable.capInsets, resizingMode: _resizable.resizingMode)
.onAppear() {
self.imageLoader.loadImage(url: self.url)
}
}
func resizable(capInsets: EdgeInsets = EdgeInsets(), resizingMode: Image.ResizingMode = .stretch) -> RemoteImage {
return RemoteImage(url: url, _resizable: (capInsets, resizingMode))
}
}
class AlamofireImageLoader: BindableObject {
var didChange = PassthroughSubject<Void, Never>()
var image = UIImage() {
didSet {
DispatchQueue.main.async {
self.didChange.send(Void())
}
}
}
convenience init(url: URLConvertible) {
self.init()
loadImage(url: url)
}
func loadImage(url: URLConvertible) {
Alamofire.request(url).responseImage { response in
if let image = response.result.value {
self.image = image
}
}
}
}
By default, SwiftUI's Image view tries to take as much space as possible and displays the entire image. We can fix this by adding resizable modifier, which resizes the image to the screen size.
resizable(capInsets:resizingMode:)Sets the mode by which SwiftUI resizes an image to fit its space.
Assuming that you are referring to the layout in storyboard/IB. To get the native size of the image just select the image and press Command + = on the keyboard. the to re-size it proportionally select the corner and hold down the shift key when you re-size it.
struct CustomImageView : View {
private var isResizable = false
var body: some View {
let image = Image("someImage")
return isResizable ? image.resizable() : image
}
func resizable() -> CustomImageView {
return CustomImageView(isResizable: true)
}
}
And use it like this.
struct ContentView: View {
var body: some View {
VStack {
CustomImageView()
.resizable()
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With