我想在這樣的UITableView單元格中顯示三角形視圖。CAShapeLayer with UIBezierPath
我設法做到這一點使用一擊代碼。
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)
}
}
雖然我正在尋找如何創建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)
但是,這根本不起作用。沒有形狀顯示。
爲了得到這個工作,我需要額外做些什麼嗎?
你必須創建一個新的上下文進行繪圖。 –