Parallelogram view using UIBezierPath
我正在尝试使用
以下是我的自定义视图代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class CustomView: UIView { override func draw(_ rect: CGRect) { let offset = 60.0; let path = UIBezierPath() path.move(to: CGPoint(x: self.frame.origin.x + CGFloat(offset), y: self.frame.origin.y)) path.addLine(to: CGPoint(x: self.frame.width + self.frame.origin.x , y: self.frame.origin.y)) path.addLine(to: CGPoint(x: self.frame.origin.x + self.frame.width - CGFloat(offset) , y: self.frame.origin.y + self.frame.height)) path.addLine(to: CGPoint(x: self.frame.origin.x, y: self.frame.origin.y + self.frame.height)) // Close the path. This will create the last line automatically. path.close() UIColor.red.setFill() path.fill() let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath self.layer.mask = shapeLayer; } } |
然后我使用
创建视图
1 2 3 | let customView = CustomView() customView.frame = CGRect(origin: CGPoint(x: 10, y: 20), size: CGSize(width: 250, height: 250)) self.view.addSubview(customView) |
但是我得到了这样的视图,它不是完美的平行四边形。
问题是在
但是也不要使用
,则可能会发生形状发生根本变化的风险。
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | @IBDesignable class CustomView: UIView { @IBInspectable var offset: CGFloat = 60 { didSet { setNeedsDisplay() } } @IBInspectable var fillColor: UIColor = .red { didSet { setNeedsDisplay() } } override func draw(_ rect: CGRect) { let path = UIBezierPath() path.move(to: CGPoint(x: bounds.minX + offset, y: bounds.minY)) path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY)) path.addLine(to: CGPoint(x: bounds.maxX - offset, y: bounds.maxY)) path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY)) // Close the path. This will create the last line automatically. path.close() fillColor.setFill() path.fill() } } |
顺便说一句,我没有设置面具。如果要设置动画,则每次调用
正如@Losiowaty所建议的,数学运算已关闭,因为右上角超出了框架的边界。 (不确定为什么clipToBounds = false不起作用;但这只是调试建议-并非解决方案)。试试这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | class CustomView: UIView { override func draw(_ rect: CGRect) { let offset: CGFloat = 60.0; let path = UIBezierPath() let width = self.bounds.width - offset let upperLeftPoint = CGPoint(x: self.bounds.origin.x + offset, y: self.bounds.origin.y) let upperRightPoint = CGPoint(x: self.bounds.origin.x + width, y: self.bounds.origin.y) let lowerRightPoint = CGPoint(x: width - offset, y: self.bounds.size.height) let lowerLeftPoint = CGPoint(x: self.bounds.origin.x, y: self.bounds.size.height) path.move(to: upperLeftPoint) path.addLine(to: upperRightPoint) path.addLine(to: lowerRightPoint) path.addLine(to: lowerLeftPoint) path.addLine(to: upperLeftPoint) // Close the path. This will create the last line automatically. path.close() UIColor.red.setFill() path.fill() let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath self.layer.mask = shapeLayer; } } |