如何制作拇指周围有曲线的自定义滑块?

问题描述 投票:0回答:1

我正在尝试实现这种滑块,以在 Swift UIKit 中围绕拇指绘制一条线。 这就是我想要实现的目标。任何人都可以指导我如何实现此目标或我可以使用任何 CocoaPods?

这就是我迄今为止所取得的成就

这是我编写的用于绘制曲线的代码:

private func drawCurvedLine() {
        
    guard let context = UIGraphicsGetCurrentContext() else { return }
        
    let trackRect = self.trackRect(forBounds: bounds)
    let thumbRect = self.thumbRect(forBounds: bounds, trackRect: trackRect, value: value)
        
    let startX = trackRect.minX - 5
    let endX = trackRect.maxX + 5
    let thumbCenterX = thumbRect.midX
    let thumbCenterY = thumbRect.minY + 10 // Start of the thumb
    let curveHeight: CGFloat = 20
    let radius: CGFloat = 20 // Radius for the curve around the thumb
        
    context.setStrokeColor(UIColor.black.cgColor)
    context.setLineWidth(1.5)
    // context.setLineCap(.round)
        
    // Line before the curve
    context.move(to: CGPoint(x: startX, y: thumbCenterY))
    context.addLine(to: CGPoint(x: thumbCenterX - radius - 5, y: thumbCenterY))
        
    // Curved line above the thumb
    context.addCurve(to: CGPoint(x: thumbCenterX + radius + 5, y: thumbCenterY),
                         control1: CGPoint(x: thumbCenterX - radius, y: thumbCenterY - curveHeight),
                         control2: CGPoint(x: thumbCenterX + radius, y: thumbCenterY - curveHeight))
        
    // Line after the curve
    context.addLine(to: CGPoint(x: endX, y: thumbCenterY))
    context.strokePath()
}
swift uikit core-graphics uislider
1个回答
1
投票

首先想象由A到E 5个点组成的4条线段,像这样:

enter image description here

如果您绘制与每对线相切的弧,您会得到与所需结果非常相似的结果。

您可以使用

addArc(tangent1End:tangent2End:radius:)
来绘制弧线。只需传入成对的点,一次每对,即
B, C
C, D
D, E

假设

rect
是我们正在绘制的
CGRect

guard let context = UIGraphicsGetCurrentContext() else { return }
context.setStrokeColor(UIColor.black.cgColor)
context.setLineWidth(1.5)

// Try playing around with the parameters below :)

// this is the vertical distance between point C and the line BD
let curveHeight = 35.0

// this is the lenght of the line BD
let triangleWidth = 100.0

// radius of the arcs
let radius = 40.0

// the y coordinate of the points A, B, D, E
let y = rect.midY

// the slider's position along the x axis as a percentage
let percentage = 0.7

let pointA = CGPoint(x: rect.minX, y: y)
let pointB = CGPoint(x: (rect.width - triangleWidth) * percentage, y: y)
let pointC = CGPoint(x: (rect.width - triangleWidth) * percentage + triangleWidth / 2, y: y - curveHeight)
let pointD = CGPoint(x: (rect.width - triangleWidth) * percentage + triangleWidth, y: y)
let pointE = CGPoint(x: rect.maxX, y: y)

context.move(to: pointA)
context.addArc(tangent1End: pointB, tangent2End: pointC, radius: radius)
context.addArc(tangent1End: pointC, tangent2End: pointD, radius: radius)
context.addArc(tangent1End: pointD, tangent2End: pointE, radius: radius)
context.addLine(to: pointE)
context.strokePath()

输出如下所示:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.