分类 quartz 2d 下的文章

swift简易画板

控制器类
//
//  ViewController.swift
//  简易画板
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var drawingBoard: DrawingBoard!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    @IBAction func back(sender: AnyObject) {
        self.drawingBoard.back()
    }
    @IBAction func clear(sender: AnyObject) {
        self.drawingBoard.clear()
    }
    @IBAction func save(sender: AnyObject) {
        self.drawingBoard.save()
    }
    @IBAction func selectColor(sender: UIButton) {
        self.drawingBoard.selectColor(sender.backgroundColor!)
    }
}
画板类
//
//  DrawingBoard.swift
//  简易画板
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
// 线结构体
struct Line {
    let color:UIColor
    var points:[CGPoint] = []
}
// 画板类,使用上下文方式画
class DrawingBoard: UIView {
    // 线的集合
    var lines:[Line] = []
    // 当前选择的颜色
    var lineColor:UIColor = UIColor.blackColor()
    // 开始触摸方法,在开始触摸的时候新初始化一个线结构体
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let tempLine = Line(color: self.lineColor, points: [])
        lines.append(tempLine)
    }
    // 移动的时候给当前的线结构体添加点
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        // 添加当前线的结构体到线集合数组
        lines[self.lines.count - 1].points.append((touch?.locationInView(touch?.view))!)
        self.setNeedsDisplay()
    }
    // 画
    override func drawRect(rect: CGRect) {
        // 先获取上下文,在添加点
        let context = UIGraphicsGetCurrentContext()
        // 设置线的样式
        CGContextSetLineCap(context, CGLineCap.Round)
        CGContextSetLineJoin(context, CGLineJoin.Round)
        CGContextSetLineWidth(context, 10)
        for var j = 0;j < self.lines.count;j++
        {
            self.lines[j].color.set()
            for var i = 0;i < self.lines[j].points.count;i++
            {
                let point:CGPoint = (self.lines[j].points[i])
                if i == 0
                {
                    CGContextMoveToPoint(context, point.x, point.y)
                }
                else
                {
                    CGContextAddLineToPoint(context, point.x, point.y)
                }
            }
            CGContextStrokePath(context)
        }
    }
    // 回退
    func back()
    {
        if self.lines.count > 0
        {
            self.lines.removeLast()
            self.setNeedsDisplay()
        }
    }
    // 清屏
    func clear()
    {
        self.lines = []
        self.setNeedsDisplay()
    }
    // 保存颜色
    func save()
    {
        // 开始位图上下文
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
        // 画图
        self.setNeedsDisplay()
        // 获取当前图片
        let context = UIGraphicsGetCurrentContext()
        self.layer.renderInContext(context!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 转换成 NSData 数据
        let resImage = UIImagePNGRepresentation(image)
        // 保存
        resImage?.writeToFile("/Users/admin/Desktop/DrawingBoard.png", atomically: true)
    }
    // 
    func selectColor(color:UIColor)
    {
        self.lineColor = color
    }
}
画板类,UIBezierPath方式画
//
//  DrawBoardBezierPath.swift
//  简易画板
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
// 线结构体,为了和之前的区分,这里的名字有点长
struct LineBezierPath {
    let color:UIColor
    var points:UIBezierPath
}
// 画板类,这个使用BezierPath画
class DrawBoardBezierPath: UIView {
    var lines:[LineBezierPath] = []
    // 当前选择的颜色
    var lineColor:UIColor = UIColor.blackColor()
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        // 初始化 UIBezierPath 对象
        let bezierPath = UIBezierPath()
        // 设置线的开始点
        bezierPath.moveToPoint((touch?.locationInView(touch?.view))!)
        // 初始化线的结构体
        let line = LineBezierPath(color: self.lineColor, points: bezierPath)
        // 添加线到线集合
        self.lines.append(line)
    }
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let touch = (touches as NSSet).anyObject()
        // 给当前的线添加点
        self.lines.last?.points.addLineToPoint((touch?.locationInView(touch?.view))!)
        self.setNeedsDisplay()
    }
    override func drawRect(rect: CGRect) {
        // 画
        for var i = 0;i < self.lines.count;i++
        {
            self.lines[i].points.lineCapStyle = CGLineCap.Round
            self.lines[i].points.lineJoinStyle = CGLineJoin.Round
            self.lines[i].points.lineWidth = 10
            self.lines[i].color.set()
            self.lines[i].points.stroke()
        }
    }
    // 回退
    func back()
    {
        if self.lines.count > 0
        {
            self.lines.removeLast()
            self.setNeedsDisplay()
        }
    }
    // 清屏
    func clear()
    {
        self.lines = []
        self.setNeedsDisplay()
    }
    // 保存颜色
    func save()
    {
        // 开始位图上下文
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
        // 画图
        self.setNeedsDisplay()
        // 获取当前图片
        let context = UIGraphicsGetCurrentContext()
        self.layer.renderInContext(context!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 转换成 NSData 数据
        let resImage = UIImagePNGRepresentation(image)
        // 保存
        resImage?.writeToFile("/Users/admin/Desktop/DrawingBoard.png", atomically: true)
    }
    //
    func selectColor(color:UIColor)
    {
        self.lineColor = color
    }
}

swift版本手势解锁

这个很有意思啊

控制器部分
//
//  ViewController.swift
//  手势解锁
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController,Gesturedelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 初始化自定义类
        let gesture = Gesture(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, 400))
        //
        gesture.backgroundColor = UIColor.clearColor()
        gesture.passwordDelegate = self
        self.view.backgroundColor = UIColor(patternImage: UIImage(imageLiteral: "Home_refresh_bg"))
        self.view.addSubview(gesture)
        // Do any additional setup after loading the view, typically from a nib.
    }
    func gestureCheckPassword(password: String) {
        if password == "0123"
        {
            let alert = UIAlertController(title: "登录成功", message: "登录成功", preferredStyle: UIAlertControllerStyle.Alert)
            alert.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
            // 用下面这个弹窗会有警告
            //let alert = UIAlertView(title: "登录成功", message: "登录成功", delegate: nil, cancelButtonTitle: "登录成功")
        }
    }
}
自定义类,解锁类,其实更多的是画图
//
//  Gesture.swift
//  手势解锁
//
//  Created by admin on 16/1/25.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
@objc protocol Gesturedelegate
{
    optional func gestureCheckPassword(password:String)
}
class Gesture: UIView {
    lazy var buttons:[UIButton] = []// 存放所有按钮
    lazy var selectedButtons:[UIButton] = []// 存放以及选择的按钮
    lazy var point:CGPoint = CGPoint(x: 0, y: 0)// 存放当前的点击的位置
    weak var passwordDelegate:Gesturedelegate!// 验证密码的代理
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 添加按钮
        for var i = 0;i < 9;i++
        {
            let button = UIButton()
            // 禁止交互,不禁止的话划过的时候会改变样式
            button.userInteractionEnabled = false
            // 设置tag,用来组合密码
            button.tag = i
            self.buttons.append(button)
            self.addSubview(button)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 设置按钮的布局
    override func layoutSubviews() {
        // 获得不同状态的图片
        let normalImage = UIImage(imageLiteral: "gesture_node_normal")
        let selectedImage = UIImage(imageLiteral: "gesture_node_highlighted")
        // 按钮的行数
        let colunm = 3
        // 根据行数计算边距
        let margin = (self.frame.size.width - (normalImage.size.width * CGFloat(colunm))) / CGFloat(colunm + 1)
        // 计算边距,利用取余和除
        for var i = 0;i < self.buttons.count;i++
        {
            let button = self.buttons[i]
            let marginLeft = CGFloat(i % colunm)
            let marginTop = CGFloat(i / colunm)
            let buttonRect = CGRectMake((marginLeft * normalImage.size.width) + (marginLeft + 1) * margin, ((marginTop + 1) * margin) + ((marginTop) * normalImage.size.height), normalImage.size.width, normalImage.size.height)
            button.frame = buttonRect
            button.setImage(normalImage, forState: UIControlState.Normal)
            button.setImage(selectedImage, forState: UIControlState.Selected)
            self.addSubview(button)
        }
    }
    // 开始点击的时候
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.touchesMoved(touches, withEvent: event)
    }
    // 设置当前连线状态
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // 获取当前touch对象
        let touch = (touches as NSSet).anyObject()
        // 获取当前触摸位置
        let location:CGPoint = (touch?.locationInView(touch?.view))!
        // 循环所有的按钮
        for var i = 0;i < self.buttons.count;i++
        {
            let button = self.buttons[i]
            // 当触摸在按钮上时,设置按钮的状态,并加入类属性,注意这里的函数
            if CGRectContainsPoint(button.frame, location) && button.selected == false
            {
                button.selected = true
                self.selectedButtons.append(button)
            }
        }
        // 追加当前触摸位置点
        self.point = location
        self.setNeedsDisplay()
    }
    // 结束触摸时做处理
    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        // 循环取消以选中的按钮状态
        self.selectedButtons.forEach({$0.selected = false})
        // 删除已经记录的所有已选中的按钮
        self.selectedButtons.removeAll()
        self.setNeedsDisplay()
    }
    // 画当前连线状态
    override func drawRect(rect: CGRect) {
        // 设置path对象
        let lines:UIBezierPath = UIBezierPath()
        // 如果没有选中则直接返回
        if self.selectedButtons.count == 0
        {
            return
        }
        // 设置起点
        lines.moveToPoint((self.selectedButtons.first?.center)!)
        // 初始化密码字符串
        var password = ""
        // 获取当前选中的按钮的点和tag
        selectedButtons.forEach({
            button in
            lines.addLineToPoint(button.center)
            password += "\(button.tag)"
        })
        // 添加当前触摸的点
        lines.addLineToPoint(self.point)
        // 设置线的格式
        lines.lineCapStyle = CGLineCap.Round
        lines.lineJoinStyle = CGLineJoin.Round
        lines.lineWidth = 10
        let lineColor = UIColor.blueColor()
        lineColor.set()
        // 画
        lines.stroke()
        // 执行密码的代理方法
        self.passwordDelegate?.gestureCheckPassword?(password)
    }
}

Quartz2d练习

在控制器中的调用

//
//  ViewController.swift
//  图形上下文
//
//  Created by zhang on 16/1/24.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // 添加自定义的view,用于测试
//        var test = Test()
//        test.frame = UIScreen.mainScreen().bounds
//        test.backgroundColor = UIColor.grayColor()
//        self.view.addSubview(test)
        // 给UITextView的文本部分添加虚线
        let textView = UITextView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
        // 取得文本
        let text = try? String(contentsOfFile: NSBundle.mainBundle().pathForResource("news", ofType: nil)!)
        textView.text = text
        textView.font = UIFont.systemFontOfSize(20)
        // 获得文本大小
        let textSize = (text as! NSString).boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.size.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:textView.font!], context: nil).size
        // 直接给 UITextView添加图片达不到效果,所以添加个view处理下
        let backgroundView = UIView(frame: CGRectMake(0, 0, textSize.width, textSize.height))
        textView.insertSubview(backgroundView, atIndex: 0)
        textView.backgroundColor = UIColor.clearColor()
        // 设置背景颜色为图片
        backgroundView.backgroundColor = UIColor(patternImage: Test.dottedLine())
        self.view.backgroundColor = UIColor(patternImage: UIImage(imageLiteral: "textBg"))
        self.view.addSubview(textView)
        // Do any additional setup after loading the view, typically from a nib.
    }
}
练习自定义类,看的话从下往上看比较好
//
//  Test.swift
//  图形上下文
//
//  Created by zhang on 16/1/24.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class Test: UIView {
    override func drawRect(rect: CGRect) {
        self.bitmapClipImage()
    }
    init()
    {
//        self.init()
        super.init(frame:CGRectMake(0, 0, 0, 0))
        // 第一种定时器
//        NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "setNeedsDisplay", userInfo: nil, repeats: true)
        // 第二种
        self.link = CADisplayLink(target: self, selector: "setNeedsDisplay")
        self.link.addToRunLoop(NSRunLoop.mainRunLoop(), forMode:NSDefaultRunLoopMode)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 画虚线
    class func dottedLine()->UIImage
    {
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(UIScreen.mainScreen().bounds.width, 10), false, 0)
        let context = UIGraphicsGetCurrentContext()
        // 这是虚线的长度会在这些里面轮换
        let lengths:[CGFloat] = [10,20,10]
        CGContextSetLineDash(context, 0, lengths, lengths.count)
        // 划线的参数
        let points:[CGPoint] = [CGPoint(x: 0, y: 5),CGPoint(x: UIScreen.mainScreen().bounds.size.width, y: 5)]
        CGContextAddLines(context, points, points.count)
        CGContextStrokePath(context)
        // 获得画好的图片
        let resImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return resImage
    }
    // 在位图中裁剪圆角图片
    func bitmapClipImage()
    {
        let image = UIImage(imageLiteral: "1")

        UIGraphicsBeginImageContextWithOptions(image.size, false, 0)
        // 在位图上下文里面获取当前上下文
        let bitmapContext = UIGraphicsGetCurrentContext()
        // 裁剪的步骤和之前的方法一样
        CGContextAddEllipseInRect(bitmapContext, CGRectMake(0, 0, image.size.width, image.size.width))
        CGContextClip(bitmapContext)
        image.drawAtPoint(CGPoint(x: 0,y: 0))
        let resImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        // 渲染
        resImage.drawAtPoint(CGPoint(x: 0, y: 0))
        // 保存
        let saveData = UIImagePNGRepresentation(resImage)
        saveData?.writeToFile("/Users/zhang/Desktop/bitmapClipImage.png", atomically: true)
    }
    // 保存当前屏幕截图
    func screen()
    {
        UIGraphicsBeginImageContextWithOptions(UIScreen.mainScreen().bounds.size, false, UIScreen.mainScreen().scale)
        // 这一步比较关键
        UIApplication.sharedApplication().windows[0].rootViewController?.view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let resImage = UIGraphicsGetImageFromCurrentImageContext()
        let saveImage = UIImagePNGRepresentation(resImage)
        UIGraphicsEndImageContext()
        saveImage!.writeToFile("/Users/zhang/Desktop/waterImage.png", atomically: true)
    }
    // 水印图片
    func waterImage()
    {
        let image = UIImage(imageLiteral: "1")
        // 开启一个位图上下文
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width, image.size.height), false, UIScreen.mainScreen().scale)
        image.drawAtPoint(CGPoint(x: 0, y: 0))
        let waterImage = UIImage(imageLiteral: "sandyBalloon")
        waterImage.drawInRect(CGRectMake(self.frame.size.width - waterImage.size.width,self.frame.size.height - waterImage.size.height,waterImage.size.width, waterImage.size.width))
        // 获得当前位图的结果
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()
        // 结束位图上下文
        UIGraphicsEndImageContext()
        // 画出结果
        resultImage.drawAtPoint(CGPoint(x: 0,y: 0))
        // 保存图片,先转换成NSData格式
        let imageData:NSData = UIImagePNGRepresentation(resultImage)!
        imageData.writeToFile("/Users/zhang/Desktop/waterImage.png", atomically: true)
    }
    // path的使用
    func path()
    {
        let context = UIGraphicsGetCurrentContext()
        // 先把路径都定义好,再往上下文里面添加
        let path = CGPathCreateMutable()
        // 添加一个圆的路径
        CGPathAddEllipseInRect(path, nil, CGRectMake(10, 10, 100, 100))
        // 添加一个矩形的路径
        CGPathAddRect(path, nil, CGRectMake(10, 100, 100, 100))
        // 一次性添加进上下文
        CGContextAddPath(context, path)
        CGContextStrokePath(context)

        // 需要注意的是,arc并不会释放c语言创建的数据,但凡是以create,retain,copy的都要realse
        // 释放的方式有几种, 然后就发现几个函数都没有。。。
    }
    // 多个气球上升
    // 气球的处事坐标
    lazy var balloonsPoint:[CGPoint] = {
        var tempPoint:[CGPoint] = []
        let marging:CGFloat = 30
        for var i = 0;i <= 6;i++
        {
            tempPoint.append(CGPoint(x: (CGFloat(i) + 1) * marging + self.ballon.size.width , y: self.frame.size.height - self.ballon.size.height))
        }
        return tempPoint
    }()
    // 气球的图片
    let ballon = UIImage(imageLiteral: "sandyBalloon")
    var link:CADisplayLink!
    func balloonsUp()
    {
//        self.balloonsPoint.forEach{
//            val in
//            self.ballon.drawAtPoint(val)
//            self.balloonsPoint[self.balloonsPoint.indexOf(val)!] = CGPoint(x: val.x,y: val.y + CGFloat(arc4random_uniform(10) / 10))
//        }
        for var i = 0;i < self.balloonsPoint.count;i++
        {
            self.ballon.drawAtPoint(self.balloonsPoint[i])
            if self.balloonsPoint[i].y <= 0 - self.ballon.size.height
            {
                self.balloonsPoint[i] = CGPoint(x: self.balloonsPoint[i].x,y: self.frame.size.height)

            }
            else
            {
                self.balloonsPoint[i] = CGPoint(x: self.balloonsPoint[i].x,y: self.balloonsPoint[i].y - CGFloat(arc4random_uniform(10)) / 2)

            }
        }
    }

    // 气球下降
    var balloonPoint = CGPoint(x: 0,y: 0)
    func balloon()
    {
        let image = UIImage(imageLiteral: "sandyBalloon")
        if self.balloonPoint.y < self.frame.size.height
        {
            self.balloonPoint = CGPoint(x: 0,y: self.balloonPoint.y + 1)
        }
        else
        {
            self.balloonPoint = CGPoint(x: 0,y: 0)
        }
        image.drawAtPoint(self.balloonPoint)
    }
    func clip()
    {
        let context = UIGraphicsGetCurrentContext()
        // 先画一个圆
        CGContextAddEllipseInRect(context, CGRectMake(self.frame.size.width * 0.1, 0, self.frame.size.width * 0.8, self.frame.size.width * 0.8))
        // 然后裁剪,这个会把除了上面圆之外的地方去掉
        CGContextClip(context)
        // 设置图片
        let image = UIImage(imageLiteral: "1")
        // 画
        image.drawInRect(CGRectMake(0, 0, image.size.width, image.size.height))
        // 画个边框
        CGContextAddEllipseInRect(context, CGRectMake(self.frame.size.width * 0.1, 0, self.frame.size.width * 0.8, self.frame.size.width * 0.8))
        // 设置下线宽
        CGContextSetLineWidth(context, 10)
        CGContextStrokePath(context)
    }
    func translation()
    {
        let context = UIGraphicsGetCurrentContext()
        // 平移,注意,平移之类的操作需要绘制之前,不然无效
        CGContextTranslateCTM(context, 100, 100)
        // 缩放
        CGContextScaleCTM(context, 2, 2)
        // 旋转
        CGContextRotateCTM(context, CGFloat(M_PI) * 0.1)
        // 一次添加多个点
        CGContextAddLines(context, [CGPoint(x: 10, y: 100),CGPoint(x: 100, y: 100),CGPoint(x: 50, y: 10)], 3)
        // 平移

        CGContextFillPath(context)
    }
    // 上下文栈的使用
    func stack()
    {
        let context = UIGraphicsGetCurrentContext()
        // 把当前上下文的状态保存到栈,比如颜色之类的
        CGContextSaveGState(context)
        CGContextSetRGBStrokeColor(context, 110/255, 110/255, 110/255, 1)
        CGContextAddRect(context, CGRectMake(10, 10, 100, 100))
        CGContextStrokePath(context)
        CGContextAddRect(context, CGRectMake(10, 200, 80, 80))
        // 恢复带之前的状态,线的颜色变成黑色
        CGContextRestoreGState(context)
        CGContextStrokePath(context)
    }
}

swift画饼状图

//
//  Pie.swift
//  小黄人
//
//  Created by admin on 16/1/23.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class Pie: UIView {
    var sections:[CGFloat] = [20,32,55,66,10,66,77,66,33,77,92,11,12]
    var colors:[UIColor] = [UIColor.whiteColor(),UIColor.blackColor(),UIColor.blueColor(),UIColor.brownColor(),UIColor.darkGrayColor(),UIColor.darkTextColor(),UIColor.redColor(),UIColor.purpleColor(),UIColor.grayColor(),UIColor.greenColor(),UIColor.yellowColor(),UIColor.orangeColor(),UIColor.magentaColor(),UIColor.lightGrayColor(),UIColor.purpleColor()]
    override func drawRect(rect: CGRect) {
        let pie = UIGraphicsGetCurrentContext()
        var sum:CGFloat = 0
        sections.forEach({sum += $0})
        print(sum)
        let radius:CGFloat = 100
        let piePoint = CGPointMake(radius, radius)
        var startAngle:CGFloat = 0
        var endAngle:CGFloat = 0
        for var i = 0;i < sections.count;i++
        {
            startAngle = endAngle
            endAngle += (sections[i] / sum) * CGFloat(M_PI * 2)
            CGContextMoveToPoint(pie, piePoint.x, piePoint.y)
            CGContextAddArc(pie, radius, radius, radius, startAngle, endAngle, 0)// 颜色显示不正确,原来是顺时针的设置问题,这个坑得记住,0是顺时针
            colors[i].set()
            CGContextFillPath(pie)
        }
    }
}

swift画小黄人

//
//  YellowMan.swift
//  小黄人
//
//  Created by admin on 16/1/23.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class YellowMan: UIView {
    override func drawRect(rect: CGRect) {
        let yellowMan = UIGraphicsGetCurrentContext()
        let viewSize = self.frame.size
        let middlePoint = CGPointMake(viewSize.width / 2, 0)
        let yellowManW = viewSize.width * 0.5
        let margin:CGFloat = 30
        // 头部圆
        let headerCircle = CGRectMake((viewSize.width - yellowManW) / 2, margin, yellowManW, yellowManW)
        CGContextSetRGBFillColor(yellowMan, 253/255, 215/255, 62/255, 1)
        CGContextAddEllipseInRect(yellowMan, headerCircle)

        // 身体矩形
        let body = CGRectMake(headerCircle.origin.x, margin + (yellowManW * 0.5) , yellowManW, yellowManW)
        CGContextAddRect(yellowMan, body)

        // 尾部圆
        let footerCircel = CGRectMake((viewSize.width - yellowManW) / 2, yellowManW + margin, yellowManW, yellowManW)
        CGContextClosePath(yellowMan)
        CGContextAddEllipseInRect(yellowMan, footerCircel)
        CGContextFillPath(yellowMan)

        // 画眼镜
        let glasserMargin:CGFloat = 5
        let glasses = CGRectMake(body.origin.x - glasserMargin, body.origin.y + glasserMargin, yellowManW + 2 * glasserMargin, yellowManW * 0.15)
        CGContextSetRGBFillColor(yellowMan, 2/255, 2/55, 6/255, 1)
        CGContextAddRect(yellowMan, glasses)
        CGContextFillPath(yellowMan)

        // 画左眼睛
        let eyeW = yellowManW * 0.8 * 0.5
        let eyeMagin = (yellowManW - (eyeW * 2)) / 2
        let leftEye = CGRectMake(body.origin.x + eyeMagin, glasses.origin.y - ((eyeW - glasses.size.height) / 2), eyeW, eyeW)
        CGContextSetRGBFillColor(yellowMan, 58/255, 58/255, 58/255, 1)
        CGContextAddEllipseInRect(yellowMan, leftEye)
        // 画右眼睛
        let rightEye = CGRectMake(body.origin.x + eyeMagin + eyeW, glasses.origin.y - ((eyeW - glasses.size.height) / 2), eyeW, eyeW)
        CGContextAddEllipseInRect(yellowMan, rightEye)
        CGContextFillPath(yellowMan)

        // 画左眼睛
        let eyeWa = eyeW * 0.8
        let eyeMagina = ((eyeW - eyeWa) * 0.5)
        let leftEyea = CGRectMake(leftEye.origin.x + eyeMagina, leftEye.origin.y + eyeMagina, eyeWa, eyeWa)
        CGContextSetRGBFillColor(yellowMan, 254/255, 254/255, 254/255, 1)
        CGContextAddEllipseInRect(yellowMan, leftEyea)
        // 画右眼睛
        let rightEyea = CGRectMake(rightEye.origin.x + eyeMagina, rightEye.origin.y + eyeMagina, eyeWa, eyeWa)
        CGContextAddEllipseInRect(yellowMan, rightEyea)
        CGContextFillPath(yellowMan)

        // 画左眼睛
        let eyeWb = eyeWa * 0.5 * 0.8
        let eyeMaginb = eyeWa * 0.5
        let leftEyeb = CGRectMake(leftEyea.origin.x + eyeMaginb, (leftEyea.size.height - eyeWb) * 0.5 + leftEyea.origin.y, eyeWb, eyeWb)
        CGContextSetRGBFillColor(yellowMan, 114/255, 28/255, 26/255, 1)
        CGContextAddEllipseInRect(yellowMan, leftEyeb)
        // 画右眼睛
        let rightEyeb = CGRectMake(rightEyea.origin.x + (eyeMaginb - eyeWb), (rightEyea.size.height - eyeWb) * 0.5 + rightEyea.origin.y, eyeWb, eyeWb)
        CGContextAddEllipseInRect(yellowMan, rightEyeb)
        CGContextFillPath(yellowMan)

        // 画左眼睛
        let eyeWc = eyeWb * 0.5
        let eyeMaginc = (eyeWb - eyeWc) * 0.5
        let leftEyec = CGRectMake(leftEyeb.origin.x + eyeMaginc, leftEyeb.origin.y + eyeMaginc, eyeWc, eyeWc)
        CGContextSetRGBFillColor(yellowMan, 0/255, 0/255, 0/255, 1)
        CGContextAddEllipseInRect(yellowMan, leftEyec)
        // 画右眼睛
        let rightEyec = CGRectMake(rightEyeb.origin.x + eyeMaginc, rightEyeb.origin.y + eyeMaginc, eyeWc, eyeWc)
        CGContextAddEllipseInRect(yellowMan, rightEyec)
        CGContextFillPath(yellowMan)

        // 画左眼睛
        let eyeWd = eyeWc * 0.5
        let eyeMagind = (eyeWc - eyeWd) * 0.5
        let leftEyed = CGRectMake(leftEyec.origin.x, leftEyec.origin.y, eyeWd, eyeWd)
        CGContextSetRGBFillColor(yellowMan, 255/255, 255/255, 255/255, 1)
        CGContextAddEllipseInRect(yellowMan, leftEyed)
        // 画右眼睛
        let rightEyed = CGRectMake(rightEyec.origin.x, rightEyec.origin.y, eyeWd, eyeWd)
        CGContextAddEllipseInRect(yellowMan, rightEyed)
        CGContextFillPath(yellowMan)


        // 画笑脸
        let smileRadius = yellowManW * 0.3
        let startAngle:Double = 0.3
        CGContextSetLineWidth(yellowMan, 2)
        CGContextAddArc(yellowMan, middlePoint.x, CGRectGetMaxY(leftEye), smileRadius, CGFloat(startAngle * M_PI), CGFloat((1 - startAngle) * M_PI), 0)
        CGContextSetRGBFillColor(yellowMan, 0/255, 0/255, 0/255, 0)
        CGContextStrokePath(yellowMan)

    }
}