Search code examples
ios8core-graphicsios9geometry

Draw circle and segments from circle


I would like to draw a circle and draw segments from this circle. Sorry because I've found a lot of topics on stackoverflow however still no one can help me understand fully. Can you give me a sample code on this? I want results like the image below. Thank you very muchenter image description here


Solution

  • Open up a new Swift 3 playground and paste the following code into it. You should see a "w 512 h 512" annotation on the right, tap on it and an eye will appear. You should see some drawing at that point.

        //: Playground - noun: a place where people can play
    import UIKit
    import CoreGraphics
    
    public func makePieChart()-> UIImage?
    {
        let size = CGSize(width: 512, height:512)
        let centerX = size.width/2.0
        let centerY = size.height/2.0
        let center = CGPoint(x: centerX, y: centerY)
        let chartRadius = size.width/2.0
    
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        defer
        {
            UIGraphicsEndImageContext()
        }
    
    
        guard let quartz = UIGraphicsGetCurrentContext() else
        {
            return nil
        }
        let π = CGFloat.pi
    
        quartz.move(to: center)
        quartz.addArc(center: center, radius: chartRadius, startAngle: 0.0, endAngle: π/3.0, clockwise: false)
        quartz.closePath() // path will complete back at the last move to (center of the circle)
    
        quartz.setFillColor(UIColor.red.cgColor)
        quartz.fillPath()
    
    
        quartz.move(to: center)
        quartz.addArc(center: center, radius: chartRadius, startAngle:  π/3.0, endAngle: π, clockwise: false)
    
        quartz.closePath() // path will complete back at the last move to (center of the circle)
    
        quartz.setFillColor(UIColor.yellow.cgColor)
        quartz.fillPath()
        quartz.move(to: center)
        quartz.addArc(center: center, radius: chartRadius, startAngle:  π, endAngle: 0.0, clockwise: false)
    
        quartz.closePath() // path will complete back at the last move to (center of the circle)
    
        quartz.setFillColor(UIColor.blue.cgColor)
        quartz.fillPath()
        return UIGraphicsGetImageFromCurrentImageContext()
    }
    
    let image = makePieChart()