首页 > 解决方案 > 有没有办法从图像形状创建精确的点击区域?

问题描述

我正在尝试创建一个交互式美国地图,但要使其发挥作用,每个州的打击区域都需要根据其形状进行精确定位。否则,用户将触发其他邻国。

附上代码。我已经搜索了所有我能找到的东西。任何的意见都将会有帮助。谢谢你。

结构地图图形:查看{

@State private var stateColor:Color = .white

var body: some View {

    ZStack {

        Image("California")
        .resizable()
        .scaledToFit()
        .colorMultiply(Color("lGrey"))
        .frame(width: 50.45, height: 87.41)

        .onTapGesture {

        switch self.stateColor {
        case .white:
            self.stateColor = .blue
        case .blue:
            self.stateColor = .red
        default:
            self.stateColor = .white
        }

        }.colorMultiply(stateColor)

    }

}

}

标签: swiftimageswiftuigesturetap

解决方案


你需要两件事:

1)在图像的矩形中构建路径(逐点)

extension Path : Shape {

    /// Describes this shape as a path within a rectangular frame of reference.
    ///
    /// - Parameter rect: The frame of reference for describing this shape.
    /// - Returns: A path that describes this shape.
    public func path(in _: CGRect) -> Path

2)将该路径(它是一个形状)设置为图像的命中测试区域

/// Returns a new view that defines the content shape for
/// hit-testing `self` as `shape`. `eoFill` defines whether the
/// shape is interpreted using the even-odd winding number rule or
/// not.
@inlinable public func contentShape<S>(_ shape: S, eoFill: Bool = false) -> some View where S : Shape

推荐阅读