贝塞尔的常用之法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了贝塞尔的常用之法相关的知识,希望对你有一定的参考价值。
对于ios常见的绘图效果都是可以用贝塞尔曲线来实现的,贝塞尔的使用分为两种情况
1,在UIView的 draw(_ rect: CGRect) 函数中是用,这个函数中默认存在上下文环境,所以可以直接显示
override func draw(_ rect: CGRect) {
let point = CGPoint.init(x: self.frame.width/2, y: self.frame.width/
let BPath = UIBezierPath.init()
BPath.addArc(withCenter: point, radius:(self.frame.width-10)/2, startAngle: 0, endAngle: CGFloat(M_PI)*CGFloat(2), clockwise: true)
BPath.lineWidth = 5
UIColor.red.setStroke()
BPath.stroke()
}
override func draw(_ rect: CGRect) {
let BPath = UIBezierPath.init(roundedRect: self.bounds, cornerRadius:
BPath.lineWidth = 5
UIColor.green.setStroke()
BPath.stroke()
}
2,贝塞尔和CAShapeLayer结合使用,借助于CAShapeLayer,贝塞尔曲线可以不用在draw(_ rect: CGRect)实现,但同时却可以显示在UIView上,此时只需要用贝塞尔曲线绘制路径,样式由CAShapeLayer进行配置
下面是一个圆形进度条
let BZpath = UIBezierPath.init(ovalIn: MyLastView.bounds)
let shaper = CAShapeLayer()
MyLastView.layer.addSublayer(shaper)
shaper.frame = MyLastView.bounds
shaper.path = BZpath.cgPath
shaper.lineWidth = 4
shaper.strokeColor = UIColor.red.cgColor
let PathAnimation = CABasicAnimation.init(keyPath: "strokeEnd")
PathAnimation.duration = 4
PathAnimation.fromValue = 0
PathAnimation.toValue = 1
PathAnimation.fillMode = kCAFillModeForwards
PathAnimation.isRemovedOnCompletion = false
PathAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseIn)
shaper.add(PathAnimation, forKey: nil)
3,View的圆角是经常要用到的,可以用
self.view.layer.cornerRadius = 10
self.view.layer.masksToBounds = true
但是,这种方法得到的是4个角都被切了,此时可以用CAShapeLayer和贝塞尔
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: roundingCorners, cornerRadii: cornerSize)
let shapeLayer = CAShapeLayer()
shapeLayer.frame = bounds
shapeLayer.path = path.cgPath
self.layer.mask = shapeLayer
4.画弧
let bottomView = UIView()
bottomView.backgroundColor = UIColor.green
bottomView.frame = CGRect.init(x: 0, y: UIScreen.main.bounds.height-200,
width: UIScreen.main.bounds.width, height: 200)
self.view.addSubview(bottomView)
let BottomPath = UIBezierPath.init()
BottomPath.move(to: CGPoint.init(x: 0, y: 50))
BottomPath.addQuadCurve(to: CGPoint.init(x: UIScreen.main.bounds.width, y: 50),
controlPoint: CGPoint.init(x: UIScreen.main.bounds.width/2, y: 0))
BottomPath.addLine(to: CGPoint.init(x: UIScreen.main.bounds.width,
y: UIScreen.main.bounds.height))
BottomPath.addLine(to: CGPoint.init(x: 0, y: UIScreen.main.bounds.height))
let bottomShape = CAShapeLayer()
bottomShape.frame = bottomView.bounds
bottomView.layer.mask = bottomShape
bottomShape.path = BottomPath.cgPath
bottomShape.lineWidth = 4
bottomShape.strokeColor = UIColor.red.cgColor
以上是关于贝塞尔的常用之法的主要内容,如果未能解决你的问题,请参考以下文章