从圆圈绘制圆圈和线段

时间:2015-10-20 17:25:12

标签: ios8 core-graphics ios9 geometry

我想绘制一个圆圈并从此圆圈中绘制线段。很抱歉,因为我在stackoverflow上发现了很多主题,但仍然没有人可以帮助我完全理解。你能给我一个示例代码吗?我想要如下图所示的结果。非常感谢enter image description here

1 个答案:

答案 0 :(得分:1)

打开一个新的Swift 3游乐场并将以下代码粘贴到其中。您应该在右侧看到“w 512 h 512”注释,点击它并出现一只眼睛。那时你应该看到一些绘图。

    //: 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()