I've been testing out SwiftUI and I guess most of you have too. I am having a weird issue, most probably a bug, but maybe someone else have found a workaround for it.
var body: some View {
Image("profilepic")
.resizable()
.aspectRatio(contentMode: .fit)
}
In a normal situation I'd expect that image to be resized and have big margins in the screen because I set the content mode to fit, if I'd use fill it will just fill the whole screen.
The fit is working fine, but the image is not keeping the aspect ratio, it shrinks.
If you have encounter this issue and know how to fix it let me know.
I also having this issue, looks like this is beta bug. I recommend to leave it as it is and wait for a fix from Apple.
If you really need to have correct Image you can create custom view struct for a SwiftUI
struct FixedImage: UIViewRepresentable {
var imageName: String
func makeUIView(context: Context) -> UIImageView {
let imageView = UIImageView(image: UIImage(named: imageName))
imageView.contentMode = .scaleAspectFit
return imageView
}
func updateUIView(_ uiView: UIImageView, context: Context) {
uiView.image = UIImage(named: imageName)
}
}
Was having the same problem trying to shrink an image down to a thumbnail for a list view... nothing was working. I also got errors trying the suggested fix from Lex above. So I modified it... Extended View Protocol with a function to calculate and return the image aspect ratio...
extension View {
func calcImageAspectRatio(_ imageName: String) -> Length?
{
if let image = UIImage(named: imageName) {
let size = image.size
return size.width / size.height
}
return nil
}
}
extension ExerciseList {
struct ExerciseCell : View {
let exercise: Exercise
var body: some View {
HStack {
Image(exercise.visuals)
.resizable()
.aspectRatio(calcImageAspectRatio(exercise.visuals), contentMode: .fit)
.frame(width: 100, height: 100, alignment: .center)
Text(exercise.title)
}
}
}
}
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