自制餅狀圖

說明:

自己寫了一個(gè)餅狀圖的控件解藻,可以旋轉(zhuǎn)(如果嫌棄旋轉(zhuǎn)范圍太窄媒鼓,可自行調(diào)節(jié))辽狈,可以出發(fā)點(diǎn)擊事件勋又。

注意:

如果視圖放在scrollView鸠蚪,或者有特定手勢存在的視圖上的時(shí)候孙咪;會(huì)出現(xiàn)旋轉(zhuǎn)不暢的現(xiàn)象宁改,如果能
解決,自行解決愉棱;解決不了可以放棄旋轉(zhuǎn)功能唆铐,或者放棄使用該控件。
ps:我是遇到了放在一個(gè)第三方的控件上羽氮,無論我怎么調(diào)整都被它影響或链,所以在公司app中,我放棄了
旋轉(zhuǎn)功能

代碼:

/**********************************/
/*********     餅狀圖     **********/
/**********************************/

class XJJPCItem {
var title: String?
var description: String?
var id: Int = 0
var scale: CGFloat = 0
var lineWidth: CGFloat = 1
var lineColor: UIColor?
var strockColor: UIColor?
var strockWidth: CGFloat = 1
var fillColor: UIColor?

//記錄值档押,不用傳入
var startAngle: CGFloat?
var endAngle: CGFloat?
var isSelected: Bool = false

init(_ title: String?,
     description: String?,
     id: Int?,
     scale: CGFloat?,
     lineWidth: CGFloat?,
     lineColor: UIColor?,
     strockColor: UIColor?,
     strockWidth: CGFloat?,
     fillColor: UIColor?) {
    self.title = title
    self.description = description
    self.id = id ?? 0
    self.scale = scale ?? 0
    self.lineWidth = lineWidth ?? 1
    self.lineColor = lineColor
    self.strockColor = strockColor
    self.strockWidth = strockWidth ?? 1
    self.fillColor = fillColor
}
}

class XJJPCView: UIView {
var touchUpBlock: ((_ id: Int) -> Void)?

var dataSource: [XJJPCItem]? {
    didSet {
        guard let data = dataSource else {return}
        self.source = data
        self.setNeedsDisplay()
    }
}

var defaultAngle: CGFloat = -1 / 4//以pi_2為基礎(chǔ)設(shè)置,-1/4即為:-pi/2
var offset: CGFloat?//位移量祈纯,用于手勢滑動(dòng)

//文字屬性
var textFont: UIFont!
var textColor: UIColor!

override init(frame: CGRect) {
    super.init(frame: frame)
    self.initUI()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touche: UITouch in touches {
        let point: CGPoint = touche.location(in: self)
        self.tap(point)
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touche: UITouch in touches {
        let point: CGPoint = touche.location(in: self)
        let previous: CGPoint = touche.previousLocation(in: self)
        if (point.x - previous.x) > 1 || (point.y - previous.y) > 1 {
            self.move(point, previous)
        }
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    
}

//移動(dòng)
private func move(_ point: CGPoint, _ previous: CGPoint) {
    let center: CGPoint = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2)
    let x: CGFloat = point.x - center.x
    let y: CGFloat = point.y - previous.y
    let per_angle: CGFloat = pi_2 / 100
    if x > 0 {
        self.diff_angle += per_angle * (y / 10)
    }else {
        self.diff_angle += -per_angle * (y / 10)
    }
    self.setNeedsDisplay()
}

//點(diǎn)擊
private func tap(_ point: CGPoint) {
    let center: CGPoint = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2)
    let x: Double = Double(point.x - center.x)
    let y: Double = Double(point.y - center.y)
    let lenght: Double = sqrt(x * x + y * y)
    let angle: CGFloat = CGFloat(acos(x / lenght))
    let d_angle: CGFloat = (y >= 0) ? angle : -angle
    let a = self.angleTranslate(d_angle)
    
    if let r = self.sectorRadius {
        let _r = Double(r)
        if x > _r || x < -_r || y > _r || y < -_r {
            return
        }
    }
    
    self.source.forEach {[weak self] (item) in
        guard let sself = self else {return}
        item.isSelected = false
        if let b = item.startAngle, let c = item.endAngle {
            if b > c {
                if (a > b && a <= pi_2) || (a < c && a > 0) {
                    sself.touchUpBlock?(item.id)
                    item.isSelected = true
                }
            }else {
                if a > b, a < c {
                    sself.touchUpBlock?(item.id)
                    item.isSelected = true
                }
            }
        }
        sself.setNeedsDisplay()
    }
}

private let pi_2 = CGFloat(Double.pi * 2)
private var sectorRadius: CGFloat?//扇形區(qū)域半徑

private var diff_angle: CGFloat = 0//旋轉(zhuǎn)時(shí)的變化量

private var source: [XJJPCItem] = []

private func initUI() {
    self.backgroundColor = UIColor.clear
    self.textFont = UIFont.boldSystemFont(ofSize: 13)
    self.textColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
}

//將角度轉(zhuǎn)化為0~pi_2之間的值
private func angleTranslate(_ angle: CGFloat) -> CGFloat {
    if angle < 0 {
        let multiple: Int = Int(-angle / pi_2) + 1
        return angle + pi_2 * CGFloat(multiple)
    }else if angle > pi_2 {
        let multiple = Int(angle / pi_2)
        return angle - pi_2 * CGFloat(multiple)
    }
    
    return angle
}

override func draw(_ rect: CGRect) {
    super.draw(rect)
    guard let current = UIGraphicsGetCurrentContext() else {return}
    
    current.clear(rect)
    current.setFillColor(UIColor.clear.cgColor)
    current.fill(rect)
    
    self.drawOnContext(current)
}

//根據(jù)數(shù)據(jù)畫出圖形
private func drawOnContext(_ context: CGContext) {
    guard source.count > 0 else {return}
    
    let center: CGPoint = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2)
    let r: CGFloat = self.bounds.height / 5 * 3 / 2
    var start: CGFloat = 0
    var end: CGFloat = 0
    
    self.sectorRadius = r
    
    var currentAngle: CGFloat = defaultAngle * pi_2 + diff_angle
    
    for item in source {
        start = currentAngle
        end = start + item.scale * pi_2
        let text: String = (item.title ?? "") + ": \(item.scale)"
        
        self.creatSector(context, center, r, start, end, item.strockWidth, item.strockColor ?? #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1), item.fillColor ?? #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1))
        let result = self.creatLine(context, center, r, start, item.scale * pi_2, item.lineColor ?? #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1), item.lineWidth)
        self.creatText(context, text, result.0, result.1)
        
        if item.isSelected == true {
            self.creatSelectSector(context, center, r + 5, start, end, 10, item.strockColor ?? #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1), item.fillColor ?? #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1))
        }
        
        currentAngle = end
        
        item.startAngle = self.angleTranslate(start)
        item.endAngle = self.angleTranslate(end)
    }
}

//畫扇形
private func creatSector(_ context: CGContext,
                         _ center: CGPoint,
                         _ radius: CGFloat,
                         _ startAngle: CGFloat,
                         _ endAngle: CGFloat,
                         _ strockWidth: CGFloat,
                         _ strockColor: UIColor,
                         _ fillColor: UIColor) {
    
    context.move(to: center)
    context.addArc(center: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
    context.setStrokeColor(strockColor.cgColor)
    context.setFillColor(fillColor.cgColor)
    context.setLineWidth(strockWidth)
    context.closePath()
    
    context.drawPath(using: .fillStroke)
}

//選中狀態(tài)圓弧
private func creatSelectSector(_ context: CGContext,
                               _ center: CGPoint,
                               _ radius: CGFloat,
                               _ startAngle: CGFloat,
                               _ endAngle: CGFloat,
                               _ strockWidth: CGFloat,
                               _ strockColor: UIColor,
                               _ fillColor: UIColor) {
    let s_color: UIColor = fillColor.withAlphaComponent(0.4)
    
    context.addArc(center: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)
    context.setStrokeColor(s_color.cgColor)
    context.setLineWidth(strockWidth)
    
    context.drawPath(using: .stroke)
}

//找到圓弧上直線經(jīng)過的點(diǎn)令宿,并返回圓心到這一點(diǎn)所在直線的任意一點(diǎn),通過scale實(shí)現(xiàn)
private func findPoint(_ center: CGPoint,
                       _ radius: CGFloat,
                       _ startAngle: CGFloat,
                       _ moveAngle: CGFloat,
                       _ scale: CGFloat) -> CGPoint {
    let angle: CGFloat = startAngle + moveAngle / 2
    let o_x: CGFloat = radius * cos(angle)
    let o_y: CGFloat = radius * sin(angle)
    let c_x: CGFloat = center.x + o_x * scale
    let c_y: CGFloat = center.y + o_y * scale
    
    return CGPoint(x: c_x, y: c_y)
}

//畫線
private func creatLine(_ context: CGContext,
                       _ center: CGPoint,
                       _ radius: CGFloat,
                       _ startAngle: CGFloat,
                       _ moveAngle: CGFloat,
                       _ lineColor: UIColor,
                       _ lineWidth: CGFloat) -> (CGPoint, Bool) {
    let centerAngle: CGFloat = self.angleTranslate(startAngle + moveAngle / 2)
    let isLeft: Bool = (centerAngle > pi_2 / 4) && (centerAngle < pi_2 / 4 * 3)
    let start: CGPoint = self.findPoint(center, radius, startAngle, moveAngle, 0.8)
    let middle: CGPoint = self.findPoint(center, radius, startAngle, moveAngle, 1.2)
    let diff: CGFloat = 1 - fabs(middle.x - center.x) / (radius * 1.2)
    let end: CGPoint = CGPoint(x: middle.x + (isLeft ? -20 : 20) * diff, y: middle.y)
    
    context.move(to: start)
    context.addLine(to: middle)
    context.addLine(to: end)
    context.setLineWidth(lineWidth)
    context.setStrokeColor(lineColor.cgColor)
    
    context.drawPath(using: .stroke)
    
    return (end, isLeft)
}

//寫文字
private func creatText(_ context: CGContext, _ text: String, _ position: CGPoint, _ isLeft: Bool) {
    let style = NSMutableParagraphStyle()
    style.lineBreakMode = .byWordWrapping
    style.alignment = .center
    
    /*之前的寫法
     let dic: [String : Any] = [
     NSFontAttributeName: textFont,
     NSForegroundColorAttributeName: textColor,
     NSParagraphStyleAttributeName: style,
     ]
     */
    
    let dic: [NSAttributedStringKey : Any] = [
        .font: textFont,
        .foregroundColor: textColor,
        .paragraphStyle: style,
        ]
    let size = text.size(withAttributes: dic)
    let x: CGFloat = isLeft ? (position.x - size.width) : position.x
    let y: CGFloat = position.y - size.height / 2
    let rect = CGRect(x: x,  y: y, width: size.width, height: size.height)
    text.draw(in: rect, withAttributes: dic)
}

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末腕窥,一起剝皮案震驚了整個(gè)濱河市粒没,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌簇爆,老刑警劉巖癞松,帶你破解...
    沈念sama閱讀 211,817評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件爽撒,死亡現(xiàn)場離奇詭異,居然都是意外死亡响蓉,警方通過查閱死者的電腦和手機(jī)硕勿,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,329評論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來枫甲,“玉大人源武,你說我怎么就攤上這事∠牖茫” “怎么了粱栖?”我有些...
    開封第一講書人閱讀 157,354評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長脏毯。 經(jīng)常有香客問我闹究,道長,這世上最難降的妖魔是什么食店? 我笑而不...
    開封第一講書人閱讀 56,498評論 1 284
  • 正文 為了忘掉前任跋核,我火速辦了婚禮,結(jié)果婚禮上叛买,老公的妹妹穿的比我還像新娘砂代。我一直安慰自己,他們只是感情好率挣,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,600評論 6 386
  • 文/花漫 我一把揭開白布刻伊。 她就那樣靜靜地躺著,像睡著了一般椒功。 火紅的嫁衣襯著肌膚如雪捶箱。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,829評論 1 290
  • 那天动漾,我揣著相機(jī)與錄音丁屎,去河邊找鬼。 笑死旱眯,一個(gè)胖子當(dāng)著我的面吹牛晨川,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播删豺,決...
    沈念sama閱讀 38,979評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼共虑,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了呀页?” 一聲冷哼從身側(cè)響起妈拌,我...
    開封第一講書人閱讀 37,722評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蓬蝶,沒想到半個(gè)月后尘分,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體猜惋,經(jīng)...
    沈念sama閱讀 44,189評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,519評論 2 327
  • 正文 我和宋清朗相戀三年培愁,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了著摔。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,654評論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡竭钝,死狀恐怖梨撞,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情香罐,我是刑警寧澤卧波,帶...
    沈念sama閱讀 34,329評論 4 330
  • 正文 年R本政府宣布,位于F島的核電站庇茫,受9級(jí)特大地震影響港粱,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜旦签,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,940評論 3 313
  • 文/蒙蒙 一查坪、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧宁炫,春花似錦偿曙、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,762評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至竿秆,卻和暖如春启摄,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背幽钢。 一陣腳步聲響...
    開封第一講書人閱讀 31,993評論 1 266
  • 我被黑心中介騙來泰國打工歉备, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人匪燕。 一個(gè)月前我還...
    沈念sama閱讀 46,382評論 2 360
  • 正文 我出身青樓蕾羊,卻偏偏與公主長得像,于是被迫代替她去往敵國和親谎懦。 傳聞我的和親對象是個(gè)殘疾皇子肚豺,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,543評論 2 349

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

  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地?cái)?shù)據(jù)庫組件 SD...
    陽明先生_X自主閱讀 15,969評論 3 119
  • ?? ?? "????" ? ???. ??? ??????, ?? ???, ??????. ??? ?? ??...
    廣井佑樹閱讀 437評論 2 2
  • 四天時(shí)間連聽帶讀界拦,完成了《魔鬼經(jīng)濟(jì)學(xué)1》,這是一本很有趣梗劫,但又很有料的書享甸。全書都在圍繞一句話在講故事截碴,那就是揭示隱...
    Winning113閱讀 179評論 0 0
  • 家里舊藏有一冊《濟(jì)慈詩選》朱維基譯本。上海譯文出版社1983年版蛉威。這一冊濟(jì)慈詩的譯本日丹,具體什么時(shí)候購買的,...
    南風(fēng)之薰專欄閱讀 750評論 2 4
  • 本周是主題作業(yè)蚯嫌,我們隊(duì)經(jīng)過討論投票最后定的家庭主題哲虾,冥思了半天時(shí)間定下了自己每天鼓勵(lì)家人至少一次的小目標(biāo),過去幾天...
    劉偉的空間閱讀 398評論 3 0