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

SwiftUI中在图像上绘制带居中文字矢量图形的实现方法

SwiftUI实现带居中文字的矢量图形方案

原生SwiftUI简便实现方法

无需依赖第三方库,用SwiftUI原生组件就能轻松实现,核心思路是利用ZStack或background组合矢量图形与文字,天然保证居中对齐。

1. 固定尺寸的图形+居中文字

适合图形大小固定,文字在其中居中的场景:

struct FixedSizeCenteredShape: View {
    let text: String
    let shapeSize: CGFloat
    let shapeColor: Color
    let textStyle: Font
    let textColor: Color
    
    var body: some View {
        ZStack {
            // 可替换为任意系统Shape:Rectangle、Capsule、RoundedRectangle等
            Circle()
                .fill(shapeColor)
                .frame(width: shapeSize, height: shapeSize)
            
            Text(text)
                .font(textStyle)
                .foregroundColor(textColor)
        }
    }
}

// 使用示例
FixedSizeCenteredShape(
    text: "24",
    shapeSize: 70,
    shapeColor: .orange,
    textStyle: .title.bold(),
    textColor: .white
)

2. 自适应尺寸的图形(随文字长度调整)

如果需要图形根据文字内容自动调整大小,用background让Shape包裹文字即可:

struct AdaptiveCenteredShape: View {
    let text: String
    let padding: CGFloat
    let shape: any Shape
    let shapeColor: Color
    let textStyle: Font
    let textColor: Color
    
    var body: some View {
        Text(text)
            .font(textStyle)
            .foregroundColor(textColor)
            .padding(padding)
            .background(
                AnyShape(shape) // 适配任意自定义Shape
                    .fill(shapeColor)
            )
    }
}

// 使用示例:自定义圆角矩形+文字
AdaptiveCenteredShape(
    text: "SwiftUI",
    padding: 12,
    shape: RoundedRectangle(cornerRadius: 8),
    shapeColor: .purple,
    textStyle: .headline,
    textColor: .white
)

3. 自定义矢量图形的适配

如果是用Path自定义的矢量图形,依然用ZStack组合,默认的居中对齐就能保证文字在图形中心:

// 自定义一个五角星Shape
struct StarShape: Shape {
    func path(in rect: CGRect) -> Path {
        var path = Path()
        // 此处可自行实现五角星的Path绘制逻辑
        return path
    }
}

// 组合自定义Shape与文字
struct CustomShapeWithText: View {
    let text: String
    
    var body: some View {
        ZStack {
            StarShape()
                .fill(.yellow)
                .frame(width: 100, height: 100)
            
            Text(text)
                .font(.largeTitle)
                .foregroundColor(.black)
        }
    }
}

可选的第三方开发库

如果想减少重复代码,快速实现更复杂的样式,这些库可以参考:

  • SwiftUIX:封装了大量实用的组合视图,包含带文字的图形组件,支持自定义Shape、文字排版和交互效果。
  • Charts:如果是数据可视化场景(比如带数值的标记图形),这个库提供了开箱即用的带文字图形组件,适配各种图表场景。
  • ShapeComponents类库:不少开源库会将Shape与文字的组合封装成可复用组件,只需传入文字、图形类型、颜色等参数即可快速生成,避免重复编写基础布局代码。

内容的提问来源于stack exchange,提问作者Sas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 06:35:22