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, quartz 2d

添加新评论