面试题答案
一键面试- 构建圆形:
- 在SwiftUI中,
Path
有一些方法可以构建常见形状。对于圆形,可以使用addArc
方法。
let circlePath = Path { path in let center = CGPoint(x: 100, y: 100) let radius: CGFloat = 50 path.addArc(center: center, radius: radius, startAngle:.degrees(0), endAngle:.degrees(360), clockwise: false) }
- 在SwiftUI中,
- 构建正方形:
- 正方形可以通过
move(to:)
和addLine(to:)
方法来构建。
let squarePath = Path { path in let startPoint = CGPoint(x: 75, y: 75) path.move(to: startPoint) path.addLine(to: CGPoint(x: 125, y: 75)) path.addLine(to: CGPoint(x: 125, y: 125)) path.addLine(to: CGPoint(x: 75, y: 125)) path.addLine(to: startPoint) }
- 正方形可以通过
- 实现动画过渡:
- 首先,定义一个状态变量来跟踪图形是否被点击,例如
@State var isSquare = false
。 - 在视图中,根据
isSquare
的值来选择要显示的Path
。
struct ContentView: View { @State var isSquare = false var body: some View { Button(action: { withAnimation { isSquare.toggle() } }) { ZStack { if isSquare { Path { path in let startPoint = CGPoint(x: 75, y: 75) path.move(to: startPoint) path.addLine(to: CGPoint(x: 125, y: 75)) path.addLine(to: CGPoint(x: 125, y: 125)) path.addLine(to: CGPoint(x: 75, y: 125)) path.addLine(to: startPoint) } .stroke(Color.blue, lineWidth: 2) } else { Path { path in let center = CGPoint(x: 100, y: 100) let radius: CGFloat = 50 path.addArc(center: center, radius: radius, startAngle:.degrees(0), endAngle:.degrees(360), clockwise: false) } .stroke(Color.blue, lineWidth: 2) } } } } }
- 首先,定义一个状态变量来跟踪图形是否被点击,例如
- 处理动画时长和曲线:
- 在
withAnimation
闭包中,可以传入Animation
实例来控制动画时长和曲线。 - 例如,设置动画时长为1秒,曲线为缓入缓出:
Button(action: { withAnimation(Animation.easeInOut(duration: 1)) { isSquare.toggle() } }) { // 视图内容 }
- 还可以使用其他曲线,如线性
Animation.linear(duration: 1)
,或者弹簧效果Animation.spring(response: 0.5, dampingFraction: 0.7, blendDuration: 0)
等。
- 在