你知道吗, CoreGraphics绘图系统和Bezier贝塞尔曲线坐标系的顺时针方向是相反的!
let content = UIGraphicsGetCurrentContext() content?.setStrokeColor(UIColor.blue.cgColor) content?.saveGState()
content?.restoreGState()
//利用上下文绘制渐变色(圆形) let context = UIGraphicsGetCurrentContext() //颜色空间 let colorSpace = CGColorSpaceCreateDeviceRGB() let startColor = UIColor.black let endColor = UIColor.red //颜色数组 let colors = [startColor.cgColor,endColor.cgColor] //颜色所处位置 let locations:[CGFloat] = [0,1] let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as! CFArray, locations: locations) let center = CGPoint(x: rect.size.width*0.5, y: rect.size.height*0.5) let radius = rect.size.height*0.3 context?.drawRadialGradient(gradient!, startCenter: center, startRadius: radius*0.2, endCenter: center, endRadius: radius, options: CGGradientDrawingOptions.drawsBeforeStartLocation)
X轴指向右侧,Y轴指向上面。对应的弧度如图上标的那样。顺时针也是钟表表针转动的方向。这就是最早接触的坐标系,熟悉的单纯模样。
在工作时,当我们往屏幕上布局UI时,用到的坐标系是下面这样:
let content = UIGraphicsGetCurrentContext() var endAngl = _progressValue*CGFloat(M_PI*2) var clockState = (_direction == .onTime) //圆 var des: String = "" des = clockState ? "UIGraphics上下文绘制、顺时针" : "UIGraphics上下文绘制、逆时针” content?.move(to: CGPoint(x: width-arcRadius, y: height*0.5)) let bez = UIBezierPath(arcCenter: arcCenter, radius: arcRadius, startAngle: 0, endAngle: endAngl, clockwise: clockState) content?.addPath(bez.cgPath) NSString(string: des).draw(in: CGRect(x: 2, y: 2, width: width*0.4, height: height*0.5), withAttributes: atts) log = String(format: "绘制弧度: %.4f Pi", endAngl/3.14) content?.strokePath()
实际效果图如下:
说出来你可能不信,你会发现顺时针方向往上了。这明明是逆时针方向啊!WTF?
来看下代码和实现效果吧。
let content = UIGraphicsGetCurrentContext() var endAngl = _progressValue*CGFloat(M_PI*2) var clockState = (_direction == .onTime) //圆 var des: String = "" des = clockState ? "UIGraphics上下文绘制、顺时针" : "UIGraphics上下文绘制、逆时针” content?.move(to: CGPoint(x: width-arcRadius, y: height*0.5)) content?.addArc(center: arcCenter, radius: arcRadius, startAngle: 0, endAngle: endAngl, clockwise: clockState) NSString(string: des).draw(in: CGRect(x: 2, y: 2, width: width*0.4, height: height*0.5), withAttributes: atts) log = String(format: "绘制弧度: %.4f Pi", endAngl/3.14) content?.strokePath()
实际效果如下:
CoreGraphics顺时针模式下,从0到2PI的效果
CoreGraphics逆时针模式下,从0到2PI的效果
CoreGraphics和Bezier贝塞尔曲线都是平时开发中的利器,认真品味一下两者的区别,会让我们对它们有更深的认识。
有讲的不对的地方欢迎指正。
Demo地址双手奉上:https://github.com/zhfei/CoordinateSystem