gpt4 book ai didi

ios - 带有 UIBezierPath 的 CAShapeLayer

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:41 24 4
gpt4 key购买 nike

我想像这样在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com