swiftui - 绘制自定义矩形
问题描述
我想制作一个顶部有两个角半径的矩形。但rectangle()
方法不支持。
我也试过GeometryReader
但不能正常工作。
解决方案
我在本文中为此编写了一个示例。最后一个例子就是这样做的。答案确实是 GeometryReader。如果您在使其工作时遇到问题,请在此处发布您的代码,以便我们为您提供帮助。
更新
以下是复制评论中包含的图像的方法:
struct ContentView : View {
var body: some View {
RoundedCorners(color: .black, tl: 35, tr: 35).frame(height: 200)
}
}
struct RoundedCorners: View {
var color: Color = .black
var tl: CGFloat = 0.0
var tr: CGFloat = 0.0
var bl: CGFloat = 0.0
var br: CGFloat = 0.0
var body: some View {
GeometryReader { geometry in
Path { path in
let w = geometry.size.width
let h = geometry.size.height
// We make sure the redius does not exceed the bounds dimensions
let tr = min(min(self.tr, h/2), w/2)
let tl = min(min(self.tl, h/2), w/2)
let bl = min(min(self.bl, h/2), w/2)
let br = min(min(self.br, h/2), w/2)
path.move(to: CGPoint(x: w / 2.0, y: 0))
path.addLine(to: CGPoint(x: w - tr, y: 0))
path.addArc(center: CGPoint(x: w - tr, y: tr), radius: tr, startAngle: Angle(degrees: -90), endAngle: Angle(degrees: 0), clockwise: false)
path.addLine(to: CGPoint(x: w, y: h - br))
path.addArc(center: CGPoint(x: w - br, y: h - br), radius: br, startAngle: Angle(degrees: 0), endAngle: Angle(degrees: 90), clockwise: false)
path.addLine(to: CGPoint(x: bl, y: h))
path.addArc(center: CGPoint(x: bl, y: h - bl), radius: bl, startAngle: Angle(degrees: 90), endAngle: Angle(degrees: 180), clockwise: false)
path.addLine(to: CGPoint(x: 0, y: tl))
path.addArc(center: CGPoint(x: tl, y: tl), radius: tl, startAngle: Angle(degrees: 180), endAngle: Angle(degrees: 270), clockwise: false)
}
.fill(self.color)
}
}
}
推荐阅读
- angular - PrimeNG p-inputnumber 无法输入负小数
- android-studio - Kotlin 4.1 MutableLiveData中'setValue'和'value'之间的区别?
- angularjs - Angular 'ng new' 命令永远存在;永远不会完成安装包
- python - 提取与数据框值匹配的正则表达式
- sublimetext3 - 有没有办法在崇高的文本中每 2-5 分钟自动保存一次?
- javascript - 如何在 redux 异步 thunk 中使用 Google Translate API?
- javascript - 生成源图的 Webpack 问题——仅在禁用特定插件时生成
- angular - 如何在 ngx-datatable 的分页中添加搜索功能?
- python - 去掉pandas中列名64个字符后的字符
- html - 为什么引导程序会影响网格行间隙?有什么方法可以预防吗?