【发布时间】:2020-02-05 22:37:10
【问题描述】:
我制作了一个按钮来匹配我的应用程序其余部分的样式,但是它太笨重了。我尝试了一些东西,但这是我所能得到的一样小。
class ButtonPath {
private let wiggle: Int = 3
func points(height: Int) ->
((Int,Int),(Int,Int),(Int,Int),
(Int,Int),(Int,Int),(Int,Int),
(Int,Int),(Int,Int),(Int,Int),
(Int,Int),(Int,Int),(Int,Int))
{
func rand() -> Int { Int.random(in: -wiggle...wiggle) }
func r2(x: Int) -> Int { Int.random(in: -x...x) }
let screen: CGRect = UIScreen.main.bounds
let widthMx = CGFloat(0.9)
let origin = (x:15, y:15)
let width = Int(screen.width * widthMx)
// Corner points
let tl = (x: origin.x + rand(), y: origin.x + rand()) // tl = Top Left, etc.
let tr = (x: origin.x + width + rand(), y: origin.y + rand())
let bl = (x: origin.x + rand(), y: origin.y + height + rand())
let br = (x: origin.x + width + rand(), y: origin.y + height + rand())
// Arc controls, we're drawing a rectangle counter-clockwise from the top left
let a1c1 = (x: origin.x + rand(), y: Int(Double(origin.y+height+rand()) * 0.3)) // a1c1 = Arc 1 Control 1
let a1c2 = (x: origin.x + rand(), y: Int(Double(origin.y+height+rand()) * 0.6))
let a2c1 = (x: Int(Double(origin.x+width+rand()) * 0.3), y: origin.y + height + rand())
let a2c2 = (x: Int(Double(origin.x+width+rand()) * 0.6), y: origin.y + height + rand())
let a3c1 = (x: origin.x + width + rand(), y: Int(Double(origin.y + height+rand()) * 0.6))
let a3c2 = (x: origin.x + width + rand(), y: Int(Double(origin.y + height+rand()) * 0.3))
let a4c1 = (x: Int(Double(origin.x+width+rand()) * 0.6), y: origin.y + rand())
let a4c2 = (x: Int(Double(origin.x+width+rand()) * 0.6), y: origin.y + rand())
return (
t1: tl, tr: tr, b1: bl, br: br,
a1c1: a1c1, a1c2: a1c2, a2c1: a2c1,
a2c2:a2c2, a3c1:a3c1, a3c2:a3c2, a4c1:a4c1, a4c2:a4c2
)
}
func path (height:Int) -> Path {
let (tl, tr, bl, br, a1c1, a1c2, a2c1, a2c2, a3c1, a3c2, a4c1, a4c2) = points(height: height)
return Path { path in
path.move( to: CGPoint(x: tl.0, y: tl.1) )
path.addCurve( to: CGPoint(x: bl.0, y: bl.1), control1: CGPoint(x: a1c1.0, y: a1c1.1), control2: CGPoint(x: a1c2.0, y: a1c2.1))
path.addCurve( to: CGPoint(x: br.0, y: br.1), control1: CGPoint(x: a2c1.0, y: a2c1.1), control2: CGPoint(x: a2c2.0, y: a2c2.1))
path.addCurve( to: CGPoint(x: tr.0, y: tr.1), control1: CGPoint(x: a3c1.0, y: a3c1.1), control2: CGPoint(x: a3c2.0, y: a3c2.1))
path.addCurve( to: CGPoint(x: tl.0-2, y: tl.1), control1: CGPoint(x: a4c1.0, y: a4c1.1), control2: CGPoint(x: a4c2.0, y: a4c2.1))
}
}
}
我可以编写一个函数来输出角、弧、路径等的值吗?
【问题讨论】:
-
那是相当简洁的代码。有时最好不要将它尽可能缩短,因为那样它又会回到不可读的状态。
-
"Bulky" 很好,只要它的可读性和可维护性。如果你认为你可以在一年内回顾这件事并了解发生了什么,那么这是一个很好的结果。就个人而言,我建议人们使用结构来制作形状,其函数计算属性为您提供形状的点。请参阅此示例:gist.github.com/amomchilov/1ac8e63001bd703cd4e460ba57b4df2f
标签: swift vector-graphics swift5