【发布时间】:2015-04-06 17:49:06
【问题描述】:
我想像这样在 UITableView 单元格中显示三角形视图。
我设法通过使用 Blow 代码完成了这项工作。
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)
但这根本行不通。没有显示任何形状。
我是否需要做任何额外的事情才能使它正常工作?
【问题讨论】:
-
你必须创建一个新的上下文来绘制。
标签: ios swift drawing uibezierpath cashapelayer