Swift中CoreGraphics的使用

CoreGraphics是一套基于C的框架,用于一切绘图操作,UIKit就是基于CoreGraphics实现的。因此它可以实现比UIKit更底层的功能。
由于最近在学swift,所以就用swift练习了一下这个类。
其实画图就是使用图形上下文和路径。不过绘图要自定义View并且重写drawRect方法。
创建路径主要有三种方式。
代码如下

import UIKit
import CoreGraphics

class CustomView: UIView {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.whiteColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func drawRect(rect: CGRect) {
        
        /*
        let ctx = UIGraphicsGetCurrentContext()
        CGContextAddArc(ctx, 200, 200, 100, 0, CGFloat(M_PI) * 2.0, 0)
        CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.9, 1.0)
        CGContextSetLineWidth(ctx, 10)
        CGContextStrokePath(ctx)
        */
        
        /*
        let ctx = UIGraphicsGetCurrentContext()
        var path = CGPathCreateMutable()
        CGPathAddArc(path, nil, 200, 200, 100, 0, CGFloat(M_PI) * 2, true)
        CGContextAddPath(ctx, path)
        CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.9, 1)
        CGContextSetLineWidth(ctx, 10)
        CGContextStrokePath(ctx)
        */
        
        let path = UIBezierPath.init(ovalInRect: CGRectMake(100, 100, 200, 200))
        var color = UIColor.init(colorLiteralRed: 0.5, green: 0.5, blue: 0.9, alpha: 1.0)
        color.setStroke()
        path.lineWidth = CGFloat(10)
        path.stroke()
        
        
    }

}

以上是自定义View中的代码,使用的时候只需要在ViewController中创建view对象并添加到屏幕上就可以了。
代码中用了三种方式绘图,不过使用最多的是第一种,大家可以根据自己的喜好使用。
代码实现的只是简单的绘制了一个圆形,就不上效果图了

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,259评论 4 61
  • 炎热的夏天,小编很是烦躁,于是乎,拿起手机看看最近有没有什么好看的剧。嗯啊,楚乔吧,谁让颖宝这么漂亮呢。看呀看,看...
    麦芽糖gogo阅读 462评论 0 2
  • 云霓第一次知道自己有个双胞胎姐妹是前年夏天。燥热的风把自己和妈妈赶到了商场里逛街,路过一家婴儿用品店时,妈妈...
    鯨魚兒阅读 373评论 0 0
  • 时光不负真情 隔壁病房住着一位老太太,和母亲做的是同样的手术。住院的第一天母亲心里没有底,让我去问问那位老太太她手...
    陶之夭夭1阅读 228评论 0 2