2016-03-02 19 views
13

Şimdiye kadar bir dolu dairem var ve bu konuyla ilgili. Memnun ve tatminsiz müşteri sayısını temsil eden ve bunu sunan bir pasta grafik yapmaya çalışıyorum. Ben CG için son derece yeni ve birileri bana bir fikir vermek veya bana rehberlik etmek için yeterli kodu krank yapabileceğini merak ediyordum.Çekirdek Grafikler kullanarak bir pasta grafik oluşturma

Alt dairenin memnun müşteri sayısını temsil etmesini ve ardından memnun olmayan müşterileri göstermek için üstüne yeni bir çevre eklemem gerekir mi? Doğru şekilde yaklaşıyor muyum?

İşte kodum şu ana kadar.

override func drawRect(rect: CGRect) { 

    // Get current context 
    let context = UIGraphicsGetCurrentContext() 

    // Set color 
    CGContextSetStrokeColorWithColor(context,UIColor(red: 0.2, green: 0.4, blue: 1, alpha: 1.0).CGColor) 

    let rectangle = CGRectMake((frame.size.width/3) - 50, frame.size.height/2 + 40,220,220) 
    CGContextAddEllipseInRect(context,rectangle) 

    CGContextSetFillColorWithColor(context, UIColor(red: 0.2, green: 0.4, blue: 1, alpha: 1.0).CGColor) 
    CGContextFillPath(context) 
    CGContextStrokePath(context) 

} 

DÜZENLEME Ayrıca

, şimdi ben memnun müşterinin toplam kapalı dayalı bir yay ile benim çember kapsayacak şekilde ihtiyaç duyabileceği görmeye başlıyorum. Kişi sayısına göre kaplama arkının boyutunu nasıl artırabilir veya azaltabilirim?

Her türlü yardım büyük takdirle karşılanacaktır!

+0

Muhtemelen şu iplik size yardımcı olabilir: [pasta grafik-arsa-in-swift] (http://stackoverflow.com/questions/28768550/pie -Chart-arsa-in-swift). – dfri

+0

Cevabı oldukça yakından araştırdım, onun kodu boş bir daireden başka bir şey üretmiyor. Ama teşekkürler. – Mihado

+1

@Ah Özniteliklere bakmadım, bu yüzden "muhtemelen" :) Gerçekten bunu kendiniz uygulamak istemediğiniz sürece, (iOS) 'dan' PieChart (...) 'a bakabilirsiniz (ya da esinlenerek). Grafikler] (https://github.com/danielgindi/ios-charts) (bu [bakınız bu eğitim] (http://www.appcoda.com/ios-charts-api-tutorial/)) veya [Swift-PieChart] (https://github.com/zemirco/swift-piechart). – dfri

cevap

36

CGContextAddArc() işlevini (Swift 3'teki CGContext.addArc()) kullanmak istersiniz. Bu, pasta grafiğinizin her segmenti için bir yay çizerek pasta grafiğiniz için birden fazla segment oluşturmanıza olanak tanır. Böyle

şey hile yapmak gerekir:

girißi yapabilirsiniz
import UIKit 

struct Segment { 

    // the color of a given segment 
    var color: UIColor 

    // the value of a given segment – will be used to automatically calculate a ratio 
    var value: CGFloat 
} 

class PieChartView: UIView { 

    /// An array of structs representing the segments of the pie chart 
    var segments = [Segment]() { 
     didSet { 
      setNeedsDisplay() // re-draw view when the values get set 
     } 
    } 

    override init(frame: CGRect) { 
     super.init(frame: frame) 
     isOpaque = false // when overriding drawRect, you must specify this to maintain transparency. 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 

    override func draw(_ rect: CGRect) { 

     // get current context 
     let ctx = UIGraphicsGetCurrentContext() 

     // radius is the half the frame's width or height (whichever is smallest) 
     let radius = min(frame.size.width, frame.size.height) * 0.5 

     // center of the view 
     let viewCenter = CGPoint(x: bounds.size.width * 0.5, y: bounds.size.height * 0.5) 

     // enumerate the total value of the segments by using reduce to sum them 
     let valueCount = segments.reduce(0, {$0 + $1.value}) 

     // the starting angle is -90 degrees (top of the circle, as the context is flipped). By default, 0 is the right hand side of the circle, with the positive angle being in an anti-clockwise direction (same as a unit circle in maths). 
     var startAngle = -CGFloat.pi * 0.5 

     for segment in segments { // loop through the values array 

      // set fill color to the segment color 
      ctx?.setFillColor(segment.color.cgColor) 

      // update the end angle of the segment 
      let endAngle = startAngle + 2 * .pi * (segment.value/valueCount) 

      // move to the center of the pie chart 
      ctx?.move(to: viewCenter) 

      // add arc from the center for each segment (anticlockwise is specified for the arc, but as the view flips the context, it will produce a clockwise arc) 
      ctx?.addArc(center: viewCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false) 

      // fill segment 
      ctx?.fillPath() 

      // update starting angle of the next segment to the ending angle of this segment 
      startAngle = endAngle 
     } 
    } 
} 

her Segment bu segmentin renk ve değerini temsil Segment yapılar, bir dizi olarak pasta grafik verileri.

Değer, herhangi bir kayan nokta olabilir ve otomatik olarak pasta grafikte kullanılacak bir orana indirgenir. Memnun müşteri sayısı vs tatminsiz sayısını temsil etmek için pasta grafiğini istiyorsanız, örneğin, sadece doğrudan değer geçirebilirsiniz kullanım

Örnek:.

let pieChartView = PieChartView() 
pieChartView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: 400) 
pieChartView.segments = [ 
    Segment(color: .red, value: 57), 
    Segment(color: .blue, value: 30), 
    Segment(color: .green, value: 25), 
    Segment(color: .yellow, value: 40) 
] 
view.addSubview(pieChartView) 

Çıktı:

enter image description here


(Bazı ekstra işlevselliği ile) Tam projesi: https://github.com/originaluser2/Pie-Chart-View

+0

Awesome, İşten eve döndüğümde ve başka sorularım olup olmadığını kontrol edeceğim. Çok teşekkür ederim! – Mihado

+0

@Mihado yardım etmek için mutlu :) arcs bazen y ekseninin ters çevrildiği gibi UIViews ile çalışırken Core Graphics'de oldukça kafa karıştırıcı olabilir, bu yüzden saat yönünde bir ark belirtmek saat yönünün tersine bir yay oluşturur ve açıları tersine çevrilir. Mutlu sahip olabileceğiniz soruları yanıtlamak için. – Hamish

+0

Bu MÜKEMMEL. Size nasıl teşekkür edeceğimi bilmiyorum. Bana izin verir vermez ödülü vereceğim. İlgilendiğinizde ne yaptığımı göstermeyi çok isterim @ originaluser2 – Mihado

İlgili konular