SwiftUI如何使用半圆遮罩裁剪图片并添加圆形背景
实现方案
你可以通过自定义Shape来实现符合要求的半圆裁剪路径,无需依赖系统自带形状,实现步骤如下:
- 先定义适配裁剪需求的自定义形状
struct ArcClipShape: Shape { func path(in rect: CGRect) -> Path { var path = Path() // 构造上半圆裁剪路径,让图片底部边缘刚好和圆形背景的上半圆弧吻合 path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: rect.width, y: 0)) path.addArc(center: CGPoint(x: rect.midX, y: rect.midY), radius: rect.width / 2, startAngle: .degrees(0), endAngle: .degrees(180), clockwise: false) path.closeSubpath() return path } }
- 替换原有代码中
clipShape的参数,同时调整图片的偏移和适配规则即可
Circle() .fill(Color.blue) .aspectRatio(contentMode: .fit) .frame(width: 48) .padding(.top, 8) .overlay( Image("product-sample1") .resizable() .scaledToFill() .frame(width: 48, height: 48) // 向上偏移半个圆形高度,让图片底部和圆形上半部分对齐 .offset(y: -24) .clipShape(ArcClipShape()) )
更优实现方案
如果不需要单独控制背景和图片的层级动画效果,可以用ZStack对齐逻辑实现,代码更简洁,性能和自定义裁剪方案完全一致:
ZStack(alignment: .top) { Circle() .fill(Color.blue) .frame(width: 48, height: 48) Image("product-sample1") .resizable() .scaledToFill() // 直接限制图片高度为圆形半径长度,无需额外裁剪 .frame(width: 48, height: 24) .clipped() } .padding(.top, 8)
内容的提问来源于stack exchange,提问作者TruMan1
相关产品推荐
相关产品推荐

