gpt4 book ai didi

ios - CAShapeLayer 凹槽路径

转载 作者:行者123 更新时间:2023-11-28 15:12:49 26 4
gpt4 key购买 nike

我想制作一个白色的 View ,里面有一个三角形的指针,如下所示:

enter image description here

如上图所示,目标是在whiteview

中创建一个“圆形凹槽”
    let pointerRadius:CGFloat = 4
pointerLayer = CAShapeLayer()
pointerLayer.path = pointerPathForContentSize(contentSize: bounds.size).cgPath
pointerLayer.lineJoin = kCALineJoinRound
pointerLayer.lineWidth = 2*pointerRadius
pointerLayer.fillColor = UIColor.white.cgColor
pointerLayer.strokeColor = UIColor.black.cgColor
pointerLayer.backgroundColor = UIColor.white.cgColor

layer.addSublayer(pointerLayer)

但我得到的是:

enter image description here

但是,如果我将描边颜色设置为白色

pointerLayer.strokeColor = UIColor.white.cgColor 

enter image description here在凹槽中,我希望在底部有一个 圆边(就像在第一张图片中一样),当 fillColor 和 strokeColor 匹配(均为白色)时,它不再可见。我该如何解决?还有其他方法可以实现吗?

指针路径的代码如下:

private func pointerPathForContentSize(contentSize: CGSize) -> UIBezierPath
{
let rect = CGRect(x: 0, y: 0, width: contentSize.width, height: contentSize.height)

let width:CGFloat = 20
let height:CGFloat = 20

let path = UIBezierPath()


let startX:CGFloat = 50
let startY:CGFloat = rect.minY
path.move(to: CGPoint(x: startX , y: startY))
path.addLine(to: CGPoint(x: (startX + width*0.5), y: startY + height))


path.addLine(to: CGPoint(x: (startX + width), y: startY))

path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
path.addLine(to: CGPoint(x: rect.minX, y: rect.minY))


path.close()
return path
}

最佳答案

由于您已经通过描边路径勾勒出您想要的形状,我认为最简单的解决方案可能是使用描边和填充路径作为 mask 。

例如,这是一个矩形的红色 View :

enter image description here

这是相同的红色 View ,顶部的凹口被切掉了。这似乎是您想要的东西:

enter image description here

我在那里做的是用一个特殊的蒙版 View 来蒙版红色 View ,该蒙版 View 使用 .clear 混合模式绘制凹口:

class MaskView : UIView {
override init(frame: CGRect) {
super.init(frame:frame)
self.isOpaque = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
let con = UIGraphicsGetCurrentContext()!
con.fill(self.bounds)
con.setBlendMode(.clear)
con.move(to: CGPoint(x:0, y:-4))
con.addLine(to: CGPoint(x:100, y:-4))
con.addLine(to: CGPoint(x:110, y:15))
con.addLine(to: CGPoint(x:120, y:-4))
con.addLine(to: CGPoint(x: self.bounds.maxX, y:-4))
con.addLine(to: CGPoint(x: self.bounds.maxX, y:-20))
con.addLine(to: CGPoint(x: 0, y:-20))
con.closePath()
con.setLineJoin(.round)
con.setLineWidth(10)
con.drawPath(using: .fillStroke) // stroke it and fill it
}
}

然后,当我准备好在红色 View 上切出凹口时,我只需说:

self.redView.mask = MaskView(frame:self.redView.bounds)

关于ios - CAShapeLayer 凹槽路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47364808/

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