//
//  ViewController.swift
//  uiBezierPath_arc_percent
//
//  Created by yoshiyuki oshige on 2015/09/19.
//  Copyright © 2015年 yoshiyuki oshige. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    // パーセントの円弧のパスを作る
    func arcPercent(radius:CGFloat, _ percent:Double) -> UIBezierPath {
        let endAngle = 2*M_PI*percent/100 - M_PI_2
        let path = UIBezierPath(
            arcCenter: CGPoint(x: 0, y: 0),
            radius: radius,
            startAngle: CGFloat(-M_PI_2),
            endAngle: CGFloat(endAngle),
            clockwise: percent>0
        )
        return path
    }
    
    func drawLine() -> UIImage {
        // イメージ処理の開始
        let size:CGSize = view.bounds.size
        UIGraphicsBeginImageContextWithOptions(size, false, 1.0)
        
        let percent = 58.2
        // 円弧のパスを作る
        UIColor.redColor().setStroke()
        let arcPath = arcPercent(80, percent)
        arcPath.lineWidth = 60
        arcPath.lineCapStyle = .Butt
        // パスを平行移動する
        let tf = CGAffineTransformMakeTranslation(view.frame.midX, view.frame.midY)
        arcPath.applyTransform(tf)
        arcPath.stroke()
        
        // 「何％」の数字を書く
        let font = UIFont.boldSystemFontOfSize(28)
        let textFontAttributes = [NSFontAttributeName: font,
            NSForegroundColorAttributeName: UIColor.grayColor()]
        let drawString = String(percent) + "%"
        let poxX = view.frame.midX - 45
        let posY = view.frame.midY - 15
        let rect = CGRect(x: poxX, y: posY, width: 90, height: 30)
        drawString.drawInRect(rect, withAttributes: textFontAttributes)
        
        // イメージコンテキストからUIImageを作る
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // イメージ処理の終了
        UIGraphicsEndImageContext()
        return image
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 図形のイメージを作る
        let drawImage = drawLine()
        // イメージビューに設定する
        let drawView = UIImageView(image: drawImage)
        // 画面に表示する
        view.addSubview(drawView)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}