Swift使用CG和CI framework画棋盘
发布时间:2020-12-14 06:40:01 所属栏目:百科 来源:网络整理
导读:一方面我们可以直接用Core Image框架画棋盘,代码如下: func drawCheckerboard(){ UIGraphicsBeginImageContextWithOptions(CGSize(width: 512 ,height: 512 ),false, 0 ) let context = UIGraphicsGetCurrentContext() context?.setFillColor(UIColor.black.
一方面我们可以直接用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的颜色对调一下即可! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |