Swift使用CG和CI framework画棋盘

一方面我们可以直接用Core Image框架画棋盘,代码如下:

func drawCheckerboard(){
        UIGraphicsBeginImageContextWithOptions(CGSize(width:512,height:512),false,0)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(UIColor.black.cgColor)

        for row in 0..<8{
            for col in 0..<8{
                if row%2 == 0{
                    if col%2 == 0{
                        context?.fill(CGRect(x: col*64,y: row*64,width: 64,height: 64))
                    }
                }else{
                    if col%2 == 1{
                        context?.fill(CGRect(x: col*64,height: 64))
                    }
                }
            }
        }

        let img = UIGraphicsGetimageFromCurrentimageContext()
        UIGraphicsEndImageContext()
        imageView.image = img
    }

效果如下:

如果各位亲懒得想复杂(复杂么?呵呵)的绘图算法,我们可以直接用CI过滤器来画棋盘,一步到位.所幸的是CI中有一个对应的过滤器CICheckerboardGenerator可以很方便的来完成以上功能!

func drawCheckerboardWithCI(){
        let context = CIContext()

        let filter = CIFilter(name: "CICheckerboardGenerator")!
        filter.setValue(CIColor.black(),forKey: "inputColor0")
        filter.setValue(CIColor.white(),forKey: "inputColor1")
        filter.setValue(64.0,forKey: "inputWidth")
        filter.setValue(CIVector(x:0,y:0),forKey: "inputCenter")

        let result = filter.outputimage!
        let cgImg = context.createCGImage(result,from: CGRect(x: 0,y: 0,width: 512,height: 512))
        imageView.image = UIImage(cgImage: cgImg!)
    }

代码很直接没啥好说的,不过倒数第二句值得提及一下.有些过滤器是不需要inputimage的,这种过滤器产生的结果图像往往面积是”无限”大小的,为了截取我们需要的图像我们需要在生成CGImage时设定实际所需的大小.

以下使用过滤器画的棋盘:

你可能会发现黑白格子次序和前一个绘制的不一样.解决也非常简单,把inputColor0和inputColor1的颜色对调一下即可!

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...