Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Image clipsToBounds

Tags:

ios

swift

swiftui

Experimenting with SwiftUI (Xcode 11.0 beta 2), I try to fill a View with an image :

Image("large")     .resizable()     .aspectRatio(contentMode: .fill)     .frame(width: 80, height: 80, alignment: .center)     .border(Color.black) 

This renders like so :

No clipping

I would like to apply something similar to UIView.clipsToBounds so the image is clipped and the parts outside of the box are not visible.

like image 407
Axel Guilmin Avatar asked Jun 30 '19 13:06

Axel Guilmin


People also ask

How do I change the size of an image in SwiftUI?

Image("name"). resizable(). scaledToFit() isn't bugged, though. So you can wrap your image in a view, adjust the frame of the view to whatever size you need, then scaledToFit() will then make the image as big as it can be while keeping aspect ratio.

How do I make an image circular in SwiftUI?

SwiftUI lets you clip any view to control its shape, all by using the clipShape() modifier. The Circle clip shape will always make circles from views, even if their width and height are unequal – it will just crop the larger value to match the small.

What is clipped SwiftUI?

In other words, clipped() applies a mask equivalent to the bound frame "rectangle", thus hiding anything that goes beyond that rectangle. SwiftUI comes with two clipped() alternatives: cornerRadius(_:) and clipShape(_:style) .


2 Answers

You can use the .clipped() modifier, which results in an effect similar to UIView.clipsToBounds:

Image("large")     .resizable()     .aspectRatio(contentMode: .fill)     .frame(width: 80, height: 80, alignment: .center)     .border(Color.black)     .clipped() // Equal to clipsToBounds = true 
like image 173
trungduc Avatar answered Sep 21 '22 11:09

trungduc


Image("large")    .resizable()    .clipShape(Circle())    .frame(width: 200.0, height: 200.0)    .overlay(Circle().stroke(Color.white,lineWidth:4).shadow(radius: 10)) 

OutPut

like image 23
Arjun Patel Avatar answered Sep 23 '22 11:09

Arjun Patel