在我们日常开发中,有很多时候遇到页面中出现曲线的时候,如果想简单点处理,一般都会让UI同事直接帮我们出一张带有曲线的图,然后用UIImageView直接贴上去,或者就自己用代码撸一套出来。大部分情况下也都了解一些绘制方法的知识,绘制曲线要么使用基于系统底层的CGContext,要么就使用UIBezierPath贝塞尔曲线。可有时运用到项目中去,又会觉得工具多了,反而不知道哪个才是最顺手的,下面咱们先来看一个效果:
实现上面的效果,总共用的还不到50行代码,可想而知,已经很实用啦,这里我把上面绘制曲线的代码贴出来,供大家参考下:
final class CardView: UIView {
/// 显示金额
var numberLab: UILabel = {
let view = UILabel()
view.backgroundColor = .white
view.transform = CGAffineTransform(translationX: 0, y: 120)
return view
}()
/// 给一个推出的动画
public func startAnimation() {
UIView.animate(withDuration: 0.3, delay: 0.3, options: .curveEaseOut, animations: {
self.numberLab.transform = CGAffineTransform.identity
}, completion: nil)
}
//构造方法中设不设置frame都可以,用约束就传frame: .zero
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(hexString: "#ee4e4e")
addSubview(numberLab)
}
required init?(coder aDecoder: NSCoder) { return nil }
override func layoutSubviews() {
super.layoutSubviews()
numberLab.frame.size = CGSize(width: 200, height: 125)
numberLab.center = CGPoint(x: bounds.midX, y: bounds.height - 62.5)
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let arcLine = UIBezierPath(ovalIn: CGRect(x: -150, y: -100, width: rect.width + 300, height: rect.height + 100))
let shapeLayer = CAShapeLayer()
shapeLayer.frame = rect
shapeLayer.position = center
shapeLayer.path = arcLine.cgPath
self.layer.mask = shapeLayer
}
}