先看效果
借鑒了這篇博客
原博客使用的 OC 寫的
在其基礎(chǔ)上增加了一些功能, 比如能隨著移動, size 也隨著改變
如何實現(xiàn)
- 如上圖, 效果是由一個大圓和一個小圓, 以及大圓触机、小圓之間的不規(guī)則圖形組成的
-
控件繼承了 UIButton, 給控件添加 pan 手勢, 當(dāng)開始移動的時候, 在原位置添加一個小圓昨寞, 然后通過下圖的方法使用貝塞爾曲線實現(xiàn)中間的不規(guī)則圖形
中間路徑實現(xiàn)代碼
//MARK: - 中間圖形路徑
private func path() -> UIBezierPath {
let center1 = smallCircleView!.center
let r1 = smallCircleView!.layer.cornerRadius
let center2 = self.center
let r2 = self.layer.cornerRadius
let d = pointToPointDistanceWithPoint1(center1, point2: center2)
let x1 = center1.x
let x2 = center2.x
let y1 = center1.y
let y2 = center2.y
let cosθ = (y2 - y1) / d
let sinθ = (x2 - x1) / d
let A = CGPointMake(x1 - r1 * cosθ, y1 + r1 * sinθ)
let B = CGPointMake(x1 + r1 * cosθ, y1 - r1 * sinθ)
let C = CGPointMake(x2 + r2 * cosθ, y2 - r2 * sinθ)
let D = CGPointMake(x2 - r2 * cosθ, y2 + r2 * sinθ)
let O = CGPointMake(A.x + d / 2 * sinθ, A.y + d / 2 * cosθ)
let P = CGPointMake(B.x + d / 2 * sinθ, B.y + d / 2 * cosθ)
let path = UIBezierPath()
path.moveToPoint(A)
path.addLineToPoint(B)
path.addQuadCurveToPoint(C, controlPoint: P)
path.addLineToPoint(D)
path.addQuadCurveToPoint(A, controlPoint: O)
return path
}
//MARK: - 兩點之間距離
private func pointToPointDistanceWithPoint1(point1: CGPoint, point2: CGPoint) ->CGFloat {
let xDistance = point2.x - point1.x
let yDistance = point2.y - point1.y
return sqrt(xDistance * xDistance + yDistance * yDistance)
}