正多邊形按鈕--可圓角可旋轉(zhuǎn)可邊框

前言

image.png

要實(shí)現(xiàn)如圖片中左側(cè)的正六邊形按鈕,其中要有邊框以及角的弧度。由于以前做過(guò)CALayer相關(guān)的功能,自然想起利用CALayer繪制path來(lái)實(shí)現(xiàn)該功能。

根據(jù)最大半徑計(jì)算各頂點(diǎn)坐標(biāo)

2460711-1410c2a76ad83148.png

先確定按鈕的size得出最大r值,然后按照這個(gè)模式得出每個(gè)點(diǎn)相對(duì)于按鈕的坐標(biāo),使用UIBezierPath繪制path得到最后的圖樣。按照這樣的邏輯確實(shí)可以做出如UI展示的效果(先忽略圓角和邊框),但是因此會(huì)引發(fā)一個(gè)問(wèn)題:這種代碼是一種死代碼。本著代碼的可擴(kuò)展性原則,在此封裝了一個(gè)多邊形按鈕

弧度計(jì)算頂點(diǎn)坐標(biāo)

  • 首先進(jìn)行一下邏輯分析,按照固定點(diǎn)坐標(biāo)的做法會(huì)導(dǎo)致代碼死板,因此換個(gè)思路進(jìn)行設(shè)計(jì): 使用角度的形式來(lái)設(shè)置對(duì)應(yīng)點(diǎn)坐標(biāo)。
  • 以按鈕的中心點(diǎn)centerPoint作為原點(diǎn),按鈕所在坐標(biāo)系的x軸上點(diǎn)(r, 0)點(diǎn)作為繪制的起始點(diǎn),依據(jù)順時(shí)針?lè)较蛞来斡?jì)算每個(gè)點(diǎn)的坐標(biāo)
  • 根據(jù)規(guī)律可知對(duì)應(yīng)弧度所表示的點(diǎn)的坐標(biāo)的x值等于centerPoint.x + r * cos(弧度),而y值等于centerPoint.y + r * sin(弧度) 該坐標(biāo)既是多邊形對(duì)應(yīng)頂點(diǎn)的坐標(biāo)

獲取單個(gè)點(diǎn)的坐標(biāo)

    private func vertexCoordinates(radius: CGFloat, angle: Double, offset: Double = 0) ->CGPoint {
        let centerPoint = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
        let X = centerPoint.x + radius * (angle + offset).cosValue
        let Y = centerPoint.y + radius * (angle + offset).sinValue
        return CGPoint(x: X, y: Y)
    }

根據(jù)多邊形的邊數(shù)、最大半徑以及偏移弧度獲得多邊形的每個(gè)頂點(diǎn)的坐標(biāo)

    private func regularPolygonCoordinates(sides: Int, radius: CGFloat, offset: Double = 0) ->[CGPoint] {
        assert(sides >= 3, "多邊形最少為3邊")
        assert(radius > 0, "多邊形半徑必須大于0")
        var coordinates = [CGPoint]()
        for i in 0..<sides {
            let corner = Double(360) / Double(sides)
            let radian = corner / Double(180) * Double.pi
            let radianOfPoint = Double(i) * radian
            let point = vertexCoordinates(radius: radius, angle: radianOfPoint, offset: offset)
            coordinates.append(point)
        }
        return coordinates
    }

再進(jìn)一步根據(jù)獲得的各個(gè)頂點(diǎn)的坐標(biāo)數(shù)組可以用UIBezierPath繪制圖案

            let points = regularPolygonCoordinates(sides: style.sides, radius: r, offset: style.offset)

            for (index, point) in points.enumerated() {
                if index == 0 {
                    path.move(to: point)
                }else {
                    path.addLine(to: point)
                }
            }
            path.close()

到現(xiàn)在只是得到了完整的path還需要設(shè)置到layer上才能變相的按該路徑裁剪按鈕

    private func hexagon() {
        var Max_R: CGFloat
        if style.Max_Radius == 0 {
            let W = bounds.width
            let H = bounds.height
            assert(W > 0 && H > 0, "此時(shí)寬或者高沒(méi)有值")
            Max_R = H > W ? W / 2 : H / 2
        }else {
            Max_R = style.Max_Radius
        }
        
        assert(Max_R > style.borderWidth, "多邊形最大半徑不能小于邊界寬度")
        
        for (index, layer) in self.layer.sublayers!.enumerated() {
            if index != 0 {
                layer.removeFromSuperlayer()
            }
        }
        
        let topLayer = CAShapeLayer()
        topLayer.path = drawPath(radius: Max_R)
        topLayer.strokeColor = style.borderColor.cgColor
        topLayer.fillColor = UIColor.clear.cgColor
        topLayer.lineWidth = style.borderWidth
        let bottomLayer = CAShapeLayer()
        bottomLayer.path = drawPath(radius: Max_R)
        
        self.layer.mask = bottomLayer
        self.layer.insertSublayer(topLayer, above: bottomLayer)
    }

然后在layoutSubviews()方法中調(diào)用該繪制方法即可獲得對(duì)應(yīng)圖形的按鈕

override func layoutSubviews() {
        super.layoutSubviews()
        
        hexagon()
    }

圓角的設(shè)置

我這里的圓角采用的不是平時(shí)按鈕的cornerRadius,而是采用的貝塞爾曲線的形式設(shè)置圓角,即根據(jù)兩個(gè)定點(diǎn)以及一個(gè)控制點(diǎn)來(lái)繪制一條有弧度的曲線,原因是多邊形如果設(shè)置cornerRadius會(huì)導(dǎo)致曲率很大最后裁剪出的弧度十分難看(不認(rèn)同的話歡迎指正)

A226DCFDDF69510054DD2C8A47A2CA48.jpg

如果把正多邊形中心點(diǎn)、頂點(diǎn)鄰近頂點(diǎn)組成的等邊三角形視為一個(gè)子模塊,選取貝塞爾曲線的固定兩點(diǎn)其一為D點(diǎn)(另一點(diǎn)以AC邊對(duì)稱)與控制點(diǎn)C,則只需要計(jì)算出D點(diǎn)對(duì)應(yīng)的坐標(biāo)即可(C點(diǎn)坐標(biāo)已知,r最大半徑已知,CD長(zhǎng)度自定義,多邊形邊數(shù)自定義)

  • 首先需要計(jì)算出∠DAC角的弧度
  • 然后計(jì)算出AD邊的大小
  • 根據(jù)普通正多邊形各頂點(diǎn)坐標(biāo)的規(guī)律計(jì)算出ADR的多邊形相對(duì)于原多邊形偏移∠DAC角度的各頂點(diǎn)坐標(biāo)
private func regularPolygonCoordinatesWithRoundedCorner(sides: Int, radius: CGFloat, offset: Double = 0) ->[CGPoint] {
        assert(sides >= 3, "多邊形最少為3邊")
        assert(radius > 0, "多邊形半徑必須大于0")
        let CAB = Double(360) / Double(sides) / Double(180) * Double.pi
        let EC = Double(radius * (CAB / 2).sinValue)
        let AE = Double(radius * (CAB / 2).cosValue)
        let ED = EC - style.filletDegree
        let EAD = atan(ED / AE)
        let DAC = CAB / 2 - EAD
        let newRadius = sqrt(pow(AE, 2) + pow(ED, 2))
        var coordinates = [CGPoint]()
        for i in 0..<sides {
            let direction = Double(i) * Double(360) / Double(sides) / Double(180) * Double.pi
            let point = vertexCoordinates(radius: radius, angle: direction, offset: offset)
            let leftAngle = direction - DAC
            let leftPoint = vertexCoordinates(radius: CGFloat(newRadius), angle: leftAngle, offset: offset)
            let rightAngle = direction + DAC
            let rightPoint = vertexCoordinates(radius: CGFloat(newRadius), angle: rightAngle, offset: offset)
            coordinates.append(leftPoint)
            coordinates.append(point)
            coordinates.append(rightPoint)
        }
        return coordinates
    }

通過(guò)上面的代碼邏輯可以計(jì)算出有圓角的多邊形的各關(guān)鍵點(diǎn)坐標(biāo),然后就只需要把這些關(guān)鍵點(diǎn)根據(jù)規(guī)律連接到一起。

let points = regularPolygonCoordinatesWithRoundedCorner(sides: style.sides, radius: r, offset: style.offset)
            var temPoint: CGPoint!
            for (index, point) in points.enumerated() {
                if index == 0 {
                    path.move(to: point)
                }else {
                    let remainder = index % 3
                    switch remainder {
                    case 0: 
                        path.addLine(to: point)
                    case 1: 
                        temPoint = point
                    case 2: 
                        path.addQuadCurve(to: point, controlPoint: temPoint)
                    default:
                        break
                    }
                }
            }
            path.close()

封裝控制屬性


class SYPolygonStyle {
    /// 是否可以圓角
    var roundedCornersEnable: Bool = false
    /// 圓角程度 - 值越大,角越平滑
    var filletDegree: Double = 5.0
    
    /// 邊界寬度(邊線的寬度)
    var borderWidth: CGFloat = 0.0
    /// 邊界顏色
    var borderColor: UIColor = UIColor.gray
    
    /// 多邊形最大半徑 -- 如果不設(shè)置該值, 默認(rèn)是按鈕中可顯示的最大多邊形的半徑
    var Max_Radius: CGFloat = 0.0
    
    /// 整個(gè)路徑以按鈕的中心點(diǎn)為中心按順時(shí)針?lè)较蚱频幕《?需要傳入一個(gè)帶π的弧度) -- 默認(rèn)六邊形頂點(diǎn)為水平方向, 如果設(shè)置該值為π/2則頂點(diǎn)為豎直方向
    var offset: Double = 0
    /// 多邊形的邊數(shù) - 默認(rèn)是正六邊形
    var sides: Int = 6
}

當(dāng)然,有了控制屬性的類沒(méi)有使用場(chǎng)景怎么行,只需要一個(gè)新的構(gòu)造方法即可

init(frame: CGRect = CGRect.zero, style: SYPolygonStyle = SYPolygonStyle()) {
        self.style = style
        super.init(frame: frame)
    }

使用方法類似于下例:

        let style = SYPolygonStyle()
        style.filletDegree = 10
        style.borderWidth = 10
        style.borderColor = .orange
        style.roundedCornersEnable = true
        style.offset = Double.pi / 4
        style.sides = 5

        let liubianxing = SYPolygonButton(frame: CGRect.zero, style: style)
        liubianxing.setImage(UIImage.init(named: "zhbd_qq_icon"), for: .normal)
        liubianxing.setImage(UIImage.init(named: "zhbd_weibo_icon"), for: .selected)
        liubianxing.addTarget(self, action: #selector(btnClickAction(sender:)), for: .touchUpInside)
        view.addSubview(liubianxing)
        liubianxing.snp.makeConstraints { (make) in
            make.top.left.equalTo(100)
            make.width.height.equalTo(100)
        }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 前言 多邊形偏移 (polygon offset) 算法可能我們印象不深,不過(guò)用過(guò) autoCAD 的同學(xué)應(yīng)該有印...
    zyl06閱讀 11,573評(píng)論 19 14
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,282評(píng)論 25 708
  • 一:canvas簡(jiǎn)介 1.1什么是canvas? ①:canvas是HTML5提供的一種新標(biāo)簽 ②:HTML5 ...
    GreenHand1閱讀 4,719評(píng)論 2 32
  • 什么也不想寫(xiě),也不知道寫(xiě)些什么,那么,今天,我就寫(xiě)一寫(xiě)自己的不想寫(xiě)吧。 從書(shū)寫(xiě)開(kāi)始的那一天,我就每每拖到晚上開(kāi)始,...
    趙婉寧閱讀 470評(píng)論 0 0
  • 緣起 2016年初,早上醒來(lái)偶爾會(huì)覺(jué)得最里面的牙有些不大舒服,但不舒服的頻率大概也就兩周一次,持續(xù)時(shí)間大概是早上上...
    出走De娜拉閱讀 5,885評(píng)論 0 1