自定义形状注册绘制路径外的水龙头 [英] Custom shape registers taps outside drawn path

查看:23
本文介绍了自定义形状注册绘制路径外的水龙头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 SwiftUI 中创建了一个自定义的 Arc 形状,但是当我向它添加一个 onTapGesture 修饰符时,它会在我为 Arc 绘制的区域之外注册点击(它在用于绘制 Arcrect 内注册 anywhere 的抽头).如何确保点击仅在 Arc 的绘制路径中注册,而不是整个 rect?

I created a custom Arc shape in SwiftUI, but when I add an onTapGesture modifier to it, it registers taps outside the area I drew for the Arc (it registers taps anywhere within the rect used to draw the Arc). How can I make sure the taps only register within the drawn path of the Arc, not the entire rect?

这是我绘制的Arc形状:

struct Arc: Shape {
  let angle: Angle
  let thickness: CGFloat
  let clockwise: Bool
  
  func path(in rect: CGRect) -> Path {
    var path = Path()
    
    let innerArcEndPoint = CGPoint(x: rect.maxX - thickness, y: 0)
    let innerArcStartPoint = CGPoint(
      x: innerArcEndPoint.x * cos(CGFloat(angle.radians)),
      y: innerArcEndPoint.x * sin(CGFloat(angle.radians)))
    
    path.move(to: innerArcStartPoint)
    path.addArc(center: rect.origin, radius: innerArcEndPoint.x, startAngle: angle, endAngle: Angle.zero, clockwise: !clockwise)
    path.addLine(to: CGPoint(x: rect.maxX, y: 0))
    path.addArc(center: rect.origin, radius: rect.maxX, startAngle: Angle.zero, endAngle: angle, clockwise: clockwise)
    path.closeSubpath()
    
    return path
  }
}

这是我使用带有 onTapGesture 修饰符的 Arc:

Here's me using the Arc with an onTapGesture modifier:

struct TestTappingArc: View {
    var body: some View {
        Arc(angle: Angle(degrees: 45), thickness: 20, clockwise: false)
          .foregroundColor(.blue) // The only area I want to be tappable
          .background(Color.orange) // The area I DON'T want to be tappable (but currently is tappable)
          .frame(width: 100, height: 100)
          .onTapGesture {
            print("hello")
          }
    }
}

这是它在屏幕上的样子:

And here's what it looks like on screen:

推荐答案

感谢 Asperi 的回答——这确实解决了问题.但是,我意识到一个更简单的解决方案是将背景移动到 after onTapGesture 修饰符,如下所示:

Thanks Asperi for that answer--that does fix the problem. However, I realized an even simpler solution is just to move the background to after the onTapGesture modifier, like this:

Arc(angle: Angle(degrees: 45), thickness: 20, clockwise: false)
  .foregroundColor(.blue)
  .frame(width: 100, height: 100)
  .onTapGesture {
    print("hello")
  }
  .background(Color.orange)

这篇关于自定义形状注册绘制路径外的水龙头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆