首页 > 解决方案 > 设计一个圆形按钮,周围有垂直线

问题描述

我正在寻找一个圆形按钮,其周围有 360 度的线条,如这里的粗略 图片所示。请查看并分享您对如何在 Android、iOS 或 Xamarin 中进行设计的想法。

谢谢

标签: androidiosxamarinxamarin.formsxamarin.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,则产生:

在此处输入图像描述


推荐阅读