gpt4 book ai didi

ios - 在箭头形面具周围绘制边框

转载 作者:可可西里 更新时间:2023-11-01 02:00:10 25 4
gpt4 key购买 nike

在我的应用程序中,我需要一个箭头轮廓,当用户进行某些事件时,它会被颜色填充。为了在我的 View 中创建一个箭头形状,我将 UIView 子类化以便在 Interface Builder 中使用:

@IBDesignable
class MaskedView: UIView {

var maskImageView = UIImageView()

@IBInspectable var maskImage: UIImage? {
didSet {
maskImageView.image = maskImage
maskImageView.contentMode = .scaleAspectFit
maskImageView.frame = bounds
mask = maskImageView
}
}

}

然后在 IB 中我选择一个箭头图像,创建所需的形状:

enter image description here

enter image description here

这里的 View 有灰色背景用于演示目的。实际上我需要它是白色的,箭头显示为黑色轮廓:

enter image description here

所以基本上我需要在我的箭头蒙版周围加一个边框。实现此结果的最佳方法是什么?

最佳答案

yourView 应该是 clearColor。在 extension 的帮助下,根据您的需要调整 CGPoint

let arrow = UIBezierPath.arrow(from: CGPoint(x: 50, y: 100), to: CGPoint(x: 200, y: 50),
tailWidth: 10, headWidth: 25, headLength: 40)
let caLay = CAShapeLayer()
caLay.path = arrow.cgPath
yourView.layer.mask = caLay

let borderLayer = CAShapeLayer()
borderLayer.path = arrow.cgPath // Reuse the Bezier path
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.strokeColor = UIColor.green.cgColor
borderLayer.lineWidth = 5
borderLayer.frame = greenview.bounds
yourView.layer.addSublayer(borderLayer)



extension UIBezierPath {

class func arrow(from start: CGPoint, to end: CGPoint, tailWidth: CGFloat, headWidth: CGFloat, headLength: CGFloat) -> Self {
let length = hypot(end.x - start.x, end.y - start.y)
let tailLength = length - headLength

func p(_ x: CGFloat, _ y: CGFloat) -> CGPoint { return CGPoint(x: x, y: y) }
var points: [CGPoint] = [
p(0, tailWidth / 2),
p(tailLength, tailWidth / 2),
p(tailLength, headWidth / 2),
p(length, 0),
p(tailLength, -headWidth / 2),
p(tailLength, -tailWidth / 2),
p(0, -tailWidth / 2)
]

let cosine = (end.x - start.x) / length
let sine = (end.y - start.y) / length
var transform = CGAffineTransform(a: cosine, b: sine, c: -sine, d: cosine, tx: start.x, ty: start.y)
let path = CGMutablePath()
path.addLines(between: points, transform: transform)
path.closeSubpath()
return self.init(cgPath: path)
}

}

关于ios - 在箭头形面具周围绘制边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47136785/

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