使用形状 SwiftUI 裁剪矩形视图
Crop Rectangle view with shape SwiftUI
我正在尝试使视图的中心部分像相机覆盖层一样透明。
如下图所示,中间部分是透明的,而其余区域是黑色不透明的。
我尝试了下面的代码。
Rectangle()
.fill(Color.red.opacity(0.5))
.mask(
Ellipse()
.fill(
Color.green.opacity(0.5)
)
.padding()
)
}
但输出是这样的。
如有任何帮助,我们将不胜感激。
谢谢
这里改编自@Asperi 的回答:
struct MaskShape : Shape {
var inset : UIEdgeInsets
func path(in rect: CGRect) -> Path {
var shape = Rectangle().path(in: rect)
shape.addPath(Ellipse().path(in: rect.inset(by: inset)))
return shape
}
}
struct ContentView : View {
var body: some View {
ZStack {
Image("2")
.resizable()
.aspectRatio(contentMode: .fill)
GeometryReader { geometry in
Color.black.opacity(0.6)
.mask(
MaskShape(
inset: UIEdgeInsets(top: geometry.size.height / 6,
left: geometry.size.width / 6,
bottom: geometry.size.height / 6,
right: geometry.size.width / 6)
).fill(style: FillStyle(eoFill: true))
)
}
}
}
}
ZStack
设置图像,然后在顶部设置半透明的黑色覆盖层。使用 eoFill
设置为 true
的遮罩将叠加层切掉。我添加了一些代码来为蒙版提供插图,因为我假设这可能是一个可变大小的蒙版。
可以更改很多细节(例如图像纵横比、插图等),但它应该可以帮助您入门。
我正在尝试使视图的中心部分像相机覆盖层一样透明。 如下图所示,中间部分是透明的,而其余区域是黑色不透明的。
我尝试了下面的代码。
Rectangle()
.fill(Color.red.opacity(0.5))
.mask(
Ellipse()
.fill(
Color.green.opacity(0.5)
)
.padding()
)
}
但输出是这样的。
如有任何帮助,我们将不胜感激。
谢谢
这里改编自@Asperi 的回答:
struct MaskShape : Shape {
var inset : UIEdgeInsets
func path(in rect: CGRect) -> Path {
var shape = Rectangle().path(in: rect)
shape.addPath(Ellipse().path(in: rect.inset(by: inset)))
return shape
}
}
struct ContentView : View {
var body: some View {
ZStack {
Image("2")
.resizable()
.aspectRatio(contentMode: .fill)
GeometryReader { geometry in
Color.black.opacity(0.6)
.mask(
MaskShape(
inset: UIEdgeInsets(top: geometry.size.height / 6,
left: geometry.size.width / 6,
bottom: geometry.size.height / 6,
right: geometry.size.width / 6)
).fill(style: FillStyle(eoFill: true))
)
}
}
}
}
ZStack
设置图像,然后在顶部设置半透明的黑色覆盖层。使用 eoFill
设置为 true
的遮罩将叠加层切掉。我添加了一些代码来为蒙版提供插图,因为我假设这可能是一个可变大小的蒙版。
可以更改很多细节(例如图像纵横比、插图等),但它应该可以帮助您入门。