android - 设计一个圆形按钮,周围有垂直线
解决方案
iOS 中的想法是子类UIButton
化并将其基础层设置为形状层,并将该形状层的路径设置为您在其中描边每条单独的线和圆的路径。例如
@IBDesignable
public class CircularButton: UIButton {
@IBInspectable public var lineWidth: CGFloat = 3 { didSet { updateShapeLayer() } }
@IBInspectable public var lineLength: CGFloat = 10 { didSet { updateShapeLayer() } }
@IBInspectable public var lineCount: Int = 48 { didSet { updateShapeLayer() } }
@IBInspectable public var insetDistance: CGFloat = 6 { didSet { updateShapeLayer() } }
@IBInspectable public var strokeColor: UIColor = .red { didSet { shapeLayer.strokeColor = strokeColor.cgColor } }
public override class var layerClass: AnyClass { return CAShapeLayer.self }
private var shapeLayer: CAShapeLayer { return layer as! CAShapeLayer }
public override func layoutSubviews() {
super.layoutSubviews()
updateShapeLayer()
}
}
private extension CircularButton {
func updateShapeLayer() {
let rect = bounds.insetBy(dx: lineWidth / 2, dy: lineWidth / 2)
let center = CGPoint(x: rect.midX, y: rect.midY)
let outerRadius = min(rect.width, rect.height) / 2
let innerRadius = outerRadius - lineLength
let circleRadius = innerRadius - insetDistance
let path = UIBezierPath()
if lineLength > 0 {
for i in 0 ..< lineCount {
let angle: CGFloat = .pi * 2 * CGFloat(i) / CGFloat(lineCount)
path.move(to: CGPoint(x: center.x + cos(angle) * outerRadius, y: center.y + sin(angle) * outerRadius))
path.addLine(to: CGPoint(x: center.x + cos(angle) * innerRadius, y: center.y + sin(angle) * innerRadius))
}
path.move(to: CGPoint(x: center.x + circleRadius, y: center.y))
}
path.addArc(withCenter: center, radius: circleRadius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
shapeLayer.lineCap = .round
shapeLayer.lineWidth = lineWidth
shapeLayer.strokeColor = strokeColor.cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.path = path.cgPath
}
}
如果按钮为 100 × 100pt,则产生:
推荐阅读
- sql - rexp_like - 似乎无法理解它是如何工作的
- javascript - 与服务器的连接不断失败连接 ETIMEDOUT 94.195.191.104:27017
- python - tensorflow 如何使用 tf.map_fn 批量处理 (?, 40,30,128) 和 (?,40,30) 的两个输入张量形状,?是我的批量大小
- isabelle - 我可以使用类和语言环境以代数方式构造一个 while 结构吗?
- php - 在 VB 中加密的 PHP 中的解密
- sql-server - 为什么 DATEDIFF 返回 -1
- python - 我们如何使用弹性搜索在 django rest 框架中获得热门搜索列表?
- powerbi - 根据组聚合不同行中的值
- scala - scala 用于 Map 的理解抛出错误
- azure - 将 Strapi 部署到 Azure