【发布时间】:2020-12-15 23:20:53
【问题描述】:
我使用CAShapeLayer 而不是CALayer 的唯一原因是动画属性。
view.layer 的红色边框是参考。如果将lineWidth 设置为shapeLayer,则该层超出red 框架。
但我希望它适合 red 框。 (适合NSView)
代码:
CustomView.swift:
class CustomView: NSView{
let shapeLayer = CAShapeLayer()
init(){
super.init(frame: .zero)
wantsLayer = true
layer?.borderWidth = 1.0
layer?.borderColor = NSColor.red.cgColor
layer?.masksToBounds = false
layer!.addSublayer(shapeLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: NSRect) {
super.draw(rect)
let path = CGMutablePath()
path.move(to: CGPoint.zero)
path.addLine(to: CGPoint(x: rect.width/2, y:rect.height))
path.addLine(to: CGPoint(x: rect.width, y: 0))
path.closeSubpath()
shapeLayer.path = path
shapeLayer.lineWidth = 30
shapeLayer.strokeColor = NSColor.lightGray.cgColor
shapeLayer.fillColor = .white
}
}
ViewController.swift
class ViewController: NSViewController {
private lazy var customView: CustomView = {
let customView = CustomView()
view.addSubview(customView)
customView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
customView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
customView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
customView.heightAnchor.constraint(equalToConstant: 144),
customView.widthAnchor.constraint(equalToConstant: 144)
])
return customView
}()
override func viewDidLoad() {
super.viewDidLoad()
customView.shapeLayer.fillColor = NSColor.systemGreen.cgColor
}
}
截图:
更新:
根据对这个问题的回答和评论。我确实通过以下代码更新了override func draw(_ rect: NSRect)
override func draw(_ rect: NSRect) {
super.draw(rect)
let path = CGMutablePath()
let lineWidth: CGFloat = 30
path.move(to: .init(x: lineWidth/2, y: lineWidth/2))
path.addLine(to: .init(x: rect.width/2, y: rect.height - lineWidth/2))
path.addLine(to: .init(x: rect.width - lineWidth/2, y: lineWidth/2))
path.closeSubpath()
shapeLayer.path = path
shapeLayer.lineWidth = lineWidth
}
CustomView.init 是,
init(){
super.init(frame: .zero)
wantsLayer = true
layer?.borderWidth = 1.0
layer?.borderColor = NSColor.red.cgColor
layer?.masksToBounds = false
layer!.addSublayer(shapeLayer)
shapeLayer.strokeColor = NSColor.lightGray.cgColor
shapeLayer.fillColor = .white
}
输出:
但我仍然无法正确绘图。
更新:
修改路径中的第一行...所以整个路径将是,
let path = CGMutablePath()
let lineWidth: CGFloat = 30
path.move(to: .init(x: lineWidth/2, y: lineWidth/2))
path.addLine(to: .init(x: rect.width/2, y: rect.height - lineWidth))
path.addLine(to: .init(x: rect.width - lineWidth/2, y: lineWidth/2))
path.closeSubpath()
现在,我对修改第二行感到困惑。我不知道如何解决它。请提示/帮助我解决这个问题。提前谢谢...
【问题讨论】:
-
改变路径,从边缘减去一半的描边宽度。
-
@ElTomato,谢谢.. 不知道该怎么做,我试过但不理解三角形的第 3 行总是越界。谢谢您的回答。但它仍然不起作用。请参阅问题中的更新。
标签: swift macos cocoa cashapelayer