我正在尝试使用创建自定义平行四边形视图UIBezierPath
但没有得到一个完美的。
以下是我的自定义视图代码
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;
}
}
我使用创建视图
let customView = CustomView()
customView.frame = CGRect(origin: CGPoint(x: 10, y: 20), size: CGSize(width: 250, height: 250))
self.view.addSubview(customView)
但我得到的视图是这样的,它不是一个完美的平行四边形。
问题是使用frame https://developer.apple.com/documentation/uikit/uiview/1622621-frame within draw(_:)
。问题是frame
是“视图的大小和位置在其父视图的坐标系中”(强调)。通常,如何在此视图中渲染此形状与此视图在其父视图中的位置无关。如果这个视图恰好不在其父视图的 0, 0 处,您可以体验裁剪。
但不要使用rect https://developer.apple.com/documentation/uikit/uiview/1622529-draw参数,或者。 “第一次绘制视图时,这个矩形通常是视图的整个可见边界。然而,在后续的绘图操作中,矩形可能只指定视图的一部分。”如果操作系统决定只需要更新您的部分内容,那么您将面临形状发生根本改变的风险CustomView
.
Use bounds https://developer.apple.com/documentation/uikit/uiview/1622580-bounds,相反,它位于视图自己的坐标系中。并且,使用minX
, minY
, maxX
, and maxY
稍微简化了代码。
@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()
}
}
顺便说一句,我没有设置面具。如果您正在制作动画,那么每次都不断地重置蒙版似乎可能效率低下draw
叫做。我个人只是将视图的背景颜色设置为.clear
。但这与眼前的问题无关。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)