ios - 带有 UIBezierPath 的 CAShapeLayer

标签 ios swift drawing uibezierpath cashapelayer

我想像这样在 UITableView 单元格中显示三角形 View 。

enter image description here

我设法使用打击代码完成了此任务。

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)

但这根本行不通。没有显示任何形状。

我需要做任何额外的事情才能让它正常工作吗?

最佳答案

你让这件事变得比它需要的更难。您只需要添加一个带有路径的形状图层,并设置该图层的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)
    }
}

关于ios - 带有 UIBezierPath 的 CAShapeLayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29476587/

相关文章:

c# - 为什么将图像写入流会产生与直接保存到文件不同的结果?

iOS 版本特定的 info.plist 设置

ios - presentedViewController 更改 KVO

ios - 将 PFQueryTableViewCell imageView 设置为本地镜像

windows-phone-7 - 如何用手指在WP7中画出形状?

OpenCV - 偏移量的DrawContour

ios - 如何检测 iPhone X 主页指示灯?

ios - 有没有资源可以让我们学习如何将不使用 Storyboard的程序修改为使用 Storyboard

ios swift 3 xcode 8 核心数据

swift - 曲线搜索栏 Swift 4