【问题标题】:Stroke a CGPath on the edges only仅在边缘上描边 CGPath
【发布时间】:2023-03-18 08:35:01
【问题描述】:

我正在使用 Swift 制作游戏,并且我有一个任意角度的 CGPath。现在让我们假设它总是一条直线。

我想要创建的是这样的:

我已经尝试过一种非常简单的方法,即以黑色粗线宽描边,复制路径,然后以背景颜色稍细的线宽再次描边。这给出了正确的外观,但最终我需要中间是透明的。

我认为这可以通过使用“父”路径(中间)的转换来实现,但我不知道该怎么做。沿单个轴的简单平移将不起作用,因为路径是倾斜的。我想我需要使用它的端点来计算路径的斜率,并使用一些数学来找到一个与父路径有一定垂直距离的点。但我不确定如何做到这一点。有什么提示,或者有其他方法吗?

编辑: 我确实尝试过使用 CGPathCreateCopyByStrokingPath,但当然它会抚摸整个路径,我真的只需要创建两条边——而不是末端。我想要这样的东西:

【问题讨论】:

  • 你的路径只是一条直线吗?
  • 是的,它是一条直线段。

标签: swift geometry cgaffinetransform cgpath


【解决方案1】:

使用CGPathCreateCopyByStrokingPath 创建一个新路径,该路径以您指定的偏移量勾勒出当前路径(偏移量是lineWidth 的一半)。然后描边那条新路径。

更新

这是一个函数,它接受一条线段(作为一对点)和一个偏移量,并返回一条与原始线段平行并偏离原始线段的新线段。

func lineSegment(segment: (CGPoint, CGPoint), offsetBy offset: CGFloat) -> (CGPoint, CGPoint) {
    let p0 = segment.0
    let p1 = segment.1

    // Compute (dx, dy) as a vector in the direction from p0 to p1, with length `offset`.
    var dx = p1.x - p0.x
    var dy = p1.y - p0.y
    let length = hypot(dx, dy)
    dx *= offset / length
    dy *= offset / length

    // Rotate the vector one quarter turn in the direction from the x axis to the y axis, so it's perpendicular to the line segment from p0 to p1.
    (dx, dy) = (-dy, dx)

    let p0Out = CGPointMake(p0.x + dx, p0.y + dy)
    let p1Out = CGPointMake(p1.x + dx, p1.y + dy)
    return (p0Out, p1Out)
}

这是一个使用它的游乐场示例:

func stroke(segment: (CGPoint, CGPoint), lineWidth: CGFloat, color: UIColor) {
    let path = UIBezierPath()
    path.moveToPoint(segment.0)
    path.addLineToPoint(segment.1)
    path.lineWidth = lineWidth
    color.setStroke()
    path.stroke()
}

let mainSegment = (CGPointMake(20, 10), CGPointMake(50, 30))
UIGraphicsBeginImageContextWithOptions(CGSizeMake(80, 60), true, 2)
UIColor.whiteColor().setFill(); UIRectFill(.infinite)
stroke(mainSegment, lineWidth: 1, color: .blackColor())
stroke(lineSegment(mainSegment, offsetBy: 10), lineWidth: 2, color: .redColor())
stroke(lineSegment(mainSegment, offsetBy: -10), lineWidth: 2, color: .blueColor())
let image = UIGraphicsGetImageFromCurrentImageContext()
XCPlaygroundPage.currentPage.captureValue(image, withIdentifier: "image")

结果:

【讨论】:

  • 见我上面的编辑。我试过了,但我认为它不适用于我的用例。
  • 这非常有效,而且超出了我的预期。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多