You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI如何使用半圆遮罩裁剪图片并添加圆形背景

实现方案

你可以通过自定义Shape来实现符合要求的半圆裁剪路径,无需依赖系统自带形状,实现步骤如下:

  1. 先定义适配裁剪需求的自定义形状
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
    }
}
  1. 替换原有代码中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:36:01