SwiftUI 图像剪辑到边界

SwiftUI Image clipsToBounds

试验 SwiftUI (Xcode 11.0 beta 2),我尝试用图像填充视图 :

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

渲染如下:

我想应用类似于 UIView.clipsToBounds 的东西,这样图像就会被裁剪掉,框外的部分就不可见了。

您可以使用 .clipped() 修饰符,其结果类似于 UIView.clipsToBounds:

Image("large")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 80, height: 80, alignment: .center)
    .border(Color.black)
    .clipped() // Equal to clipsToBounds = true
Image("large")
   .resizable()
   .clipShape(Circle())
   .frame(width: 200.0, height: 200.0)
   .overlay(Circle().stroke(Color.white,lineWidth:4).shadow(radius: 10))

Use GeometryReader can fix the issue where if the clipped region of the image overlaps a button, that button will NOT work

like this:
GeometryReader { geo in
   Image("large")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 80, height: 80, alignment: .center)
    .border(Color.black)
 }.frame(width: 150, height: hh)
Image("large")
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(width: 80, height: 80, alignment: .center)
+   .contentShape(Rectangle())
+   .clipped()
    .border(Color.black)

这帮助我解决了图像重叠按钮的问题。 contentShape() 用于剪辑 hit-testing 区域。 clipped() 正在裁剪视图边界内的内容(正如其他人提到的)。