Isu*_*uru 5 drawing cashapelayer ios uibezierpath swift
我想在这样的UITableView单元格中显示三角形视图.

我设法使用吹码完成了这个.
import UIKit
class TriangleView: UIView {
override func drawRect(rect: CGRect) {
let width = self.layer.frame.width
let height = self.layer.frame.height
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 0, 0)
CGPathAddLineToPoint(path, nil, width, 0)
CGPathAddLineToPoint(path, nil, 0, height)
CGPathAddLineToPoint(path, nil, 0, 0)
CGPathCloseSubpath(path)
let mask = CAShapeLayer()
mask.frame = self.layer.bounds
mask.path = path
self.layer.mask = mask
let shape = CAShapeLayer()
shape.frame = self.bounds
shape.path = path
shape.fillColor = UIColor.clearColor().CGColor
self.layer.insertSublayer(shape, atIndex: 0)
}
}
Run Code Online (Sandbox Code Playgroud)
当我在UIViews中搜索如何创建形状时,我发现你可以使用UIBezierPath它来做同样的事情.所以我尝试使用相同的东西复制UIBezierPath.
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 0, y: 0))
path.moveToPoint(CGPoint(x: width, y: 0))
path.moveToPoint(CGPoint(x: 0, y: height))
path.moveToPoint(CGPoint(x: 0, y: 0))
path.closePath()
let mask = CAShapeLayer()
mask.frame = self.bounds
mask.path = path.CGPath
self.layer.mask = mask
let shape = CAShapeLayer()
shape.frame = self.bounds
shape.path = path.CGPath
shape.fillColor = UIColor.clearColor().CGColor
self.layer.insertSublayer(shape, atIndex: 0)
Run Code Online (Sandbox Code Playgroud)
但这根本行不通.没有形状显示出来.
我是否需要做额外的工作以使其正常工作?
你正在努力使它变得更加困难.您只需要添加带路径的形状图层,然后设置该fillColor图层.你的代码不起作用的主要原因是因为你使用的moveToPoint是所有行而不是addLineToPoint除了第一行之外的所有行.
class TriangleView: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 0, y: 0))
path.addLineToPoint(CGPoint(x: frame.size.width, y: 0))
path.addLineToPoint(CGPoint(x: 0, y: frame.size.height))
path.closePath()
let shape = CAShapeLayer()
shape.frame = self.bounds
shape.path = path.CGPath
shape.fillColor = UIColor.blueColor().CGColor
self.layer.addSublayer(shape)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6951 次 |
| 最近记录: |