Rob*_*b13 5 core-graphics cashapelayer ios uibezierpath swift
我正在尝试将自定义形状添加到imageView. 请检查以下图片。
这是必需的:
这是我到目前为止所做的:
我是新手,Core Graphics到目前为止我已经做到了:
private func customImageClipper(imageV: UIImageView){
let path = UIBezierPath()
let size = imageV.frame.size
print(size)
path.move(to: CGPoint(x: 0.0, y: size.height))
path.addLine(to: CGPoint(x: 0.8, y: size.height/2))
path.close()
let shape = CAShapeLayer()
shape.path = path.cgPath
imageV.layer.sublayers = [shape]
}
Run Code Online (Sandbox Code Playgroud)
我正在创建一个函数来实现这样的形状,但是每当我将 传递给imageView这个函数时,我根本看不到任何变化。我知道我必须从一个点移动到另一个点才能达到这个形状,但我从来没有这样做过。任何帮助,将不胜感激。这就是我调用这个函数的方式:
imageV.layoutIfNeeded()
customImageClipper(imageV: imageV)
Run Code Online (Sandbox Code Playgroud)
PS:我没有使用Storyboard,我以编程方式创建了这个。
有很多方法可以使用 UIBezierPaths 创建形状。此处的这篇文章讨论了使用该draw函数创建形状。
这是clip在单元格中使用您的函数的示例。
func clip(imageView: UIView, withOffset offset: CGFloat) {
let path = UIBezierPath()
//Move to Top Left
path.move(to: .init(x: imageView.bounds.size.width * offset, y: 0))
//Draw line from Top Left to Top Right
path.addLine(to: .init(x: imageView.bounds.size.width, y: 0))
//Draw Line from Top Right to Bottom Right
path.addLine(to: .init(x: imageView.bounds.size.width * (1 - offset), y: imageView.bounds.size.height))
//Draw Line from Bottom Right to Bottom Left
path.addLine(to: .init(x: 0, y: imageView.bounds.size.height))
//Close Path
path.close()
//Create the Shape Mask for the ImageView
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.black.cgColor
imageView.layer.mask = shapeLayer
}
Run Code Online (Sandbox Code Playgroud)
在这个函数中,偏移量是你想要的形状的角度量,范围从 0 到 1。(0.4) 似乎适合你的要求。
这与 Apseri 的答案有很多相似之处,除了我选择了百分比路线,而不是确切大小。这两种方法都没有错,我只是发现百分比更容易理解。:)
最后要指出的是,我在函数中使用了这个layoutSubviews函数。
override func layoutSubviews() {
super.layoutSubviews()
imageView.layoutIfNeeded()
clip(imageView: self.imageView, withOffset: 0.4)
}
Run Code Online (Sandbox Code Playgroud)
这输出以下图像:
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
1140 次 |
| 最近记录: |