Style — cornerRadius
This article is extracted from the chat log with AI. Please identify it with caution.

cornerRadius is Deprecateds. Use clipShape(_:style:) or fill(style:) instead.

在 SwiftUI 中,cornerRadius 是一个常用的修饰符,用于为视图添加圆角效果,提升界面美观度。以下是它的使用场景、使用方法和代码示例:


使用场景 #

  1. 按钮和卡片设计:为按钮或卡片添加圆角,使其更符合现代 UI 设计风格。
  2. 头像或图片:将图片裁剪为圆角或圆形(例如用户头像)。
  3. 输入框和弹窗:柔化文本框或弹窗的边角。
  4. 自定义形状控件:结合其他修饰符创建复杂形状。

基本用法 #

通过 .cornerRadius(_:) 修饰符直接应用圆角,参数是圆角的半径值。

代码示例 1:基础圆角 #

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, SwiftUI!")
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(10) // 设置圆角半径为 10
    }
}

效果:一个蓝色背景、白色文字、圆角半径为 10 的文本框。


进阶用法 #

1. 圆形裁剪(头像) #

通过设置 cornerRadius 为宽度的一半,可以将视图裁剪为圆形:

Image("avatar") // 假设有一张名为 "avatar" 的图片
    .resizable()
    .frame(width: 100, height: 100)
    .cornerRadius(50) // 宽度的一半,裁剪为圆形
    // 或直接使用 .clipShape(Circle())

2. 组合裁剪与边框 #

Button(action: {}) {
    Text("点击按钮")
        .padding()
        .background(Color.green)
        .cornerRadius(8) // 圆角
        .overlay(
            RoundedRectangle(cornerRadius: 8) // 与圆角匹配的边框
                .stroke(Color.white, lineWidth: 2)
        )
}

3. 卡片式布局 #

VStack {
    Image("landscape")
        .resizable()
        .aspectRatio(contentMode: .fit)
        .cornerRadius(20, corners: [.topLeft, .topRight]) // 仅顶部圆角(需扩展)
    Text("风景图片")
        .padding()
}
.background(Color.white)
.cornerRadius(20) // 整体卡片圆角
.shadow(radius: 5)

自定义圆角位置(扩展) #

SwiftUI 默认会对四个角应用圆角,若需仅对部分角生效,可以通过扩展实现:

// 扩展代码
extension View {
    func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
        clipShape(RoundedCorner(radius: radius, corners: corners))
    }
}

struct RoundedCorner: Shape {
    var radius: CGFloat = .infinity
    var corners: UIRectCorner = .allCorners

    func path(in rect: CGRect) -> Path {
        let path = UIBezierPath(
            roundedRect: rect,
            byRoundingCorners: corners,
            cornerRadii: CGSize(width: radius, height: radius)
        )
        return Path(path.cgPath)
    }
}

// 使用示例:仅左上和右上圆角
Text("自定义圆角")
    .padding()
    .background(Color.orange)
    .cornerRadius(20, corners: [.topLeft, .topRight])

注意事项 #

  1. 裁剪超出部分:如果圆角外的内容需要隐藏,确保父视图有足够的空间或使用 .clipped()
  2. 性能优化:过度复杂的圆角组合可能影响渲染性能。
  3. 动态适配:结合 GeometryReader 可实现根据屏幕尺寸动态调整圆角。

通过灵活使用 cornerRadius,你可以轻松实现丰富的界面设计效果!

本文共 744 字,创建于 Apr 13, 2025
相关标签: Xcode, SwiftUI, ByAI