【问题标题】:Snaping Puzzle Pieces like MIT Scratch像 MIT Scratch 这样的拼图
【发布时间】:2016-11-03 03:31:07
【问题描述】:

我正在尝试创建一种拼图界面,其中块可以轻松地拼接在一起。该接口类似于MIT scratch 之类的接口,因为如果需要容纳更多块,则该块需要能够扩展。我想知道这样做的好方法是什么,或者是否已经存在类似的东西?

到目前为止,我对如何实现这一点的想法是让块只是用户可以拖动的 UIView。如果它们彼此靠近,我会让它们合在一起。至于扩展部分,这有点棘手,我可以让这些块由 3 个视图组成。当需要更多空间时,我可以扩大中间部分和间隙并安装块。无论如何,这似乎实施起来非常乏味,而且老实说似乎没有那么有效。是否没有我可以搭载的现有对象/开源库来简化此操作?

【问题讨论】:

  • 我认为效率不应该是您主要关心的问题,因为用户与 UI 元素的交互不会对 CPU 造成负担。
  • 请张贴您的代码图片或一些材料来帮助我们?你的问题不是很清楚...

标签: ios swift user-interface interface


【解决方案1】:

我不知道有什么库可以为你神奇地做到这一点,但我会做的是有一个打开连接的列表,其中一个块或一块可以适合,当你释放鼠标按钮时,你拥有的一块selected 到最近的位置(使用勾股定理求距离)。也许你有一个阈值距离,块实际上没有卡到位。是的,扩展会稍微困难一些,但最后你可以只使用一个 CGPath,当函数中放置一些东西时,它会重新绘制。

这里有一个例子。

extension CGPoint {
    func distanceTo(_ other:CGPoint) -> CGFloat {
        return CGFloat(sqrt((pow(other.x - self.x, 2) + pow(other.y - self.y, 2))))
    }
}

这将是我粘贴到大多数程序中的距离函数。

var pieces:[NSView]!//The Pieces on the board/screen
var SelectedPiece:NSView!//the piece you are holding, could also be an index.
override func mouseUp(with event: NSEvent) {
    var spaces:[CGPoint] = []
    for piece in pieces {
        spaces.append(CGPoint(x: piece.frame.origin.x, y: piece.frame.origin.y + 20))//change 20 to whatever
        spaces.append(CGPoint(x: piece.frame.origin.x, y: piece.frame.origin.y - 20))
        //if you are actually making a puzzle you might want pieces on the sides.
    }
    var ClosestDist:CGFloat?
    var ClosestIndex:Int?
    for space in spaces {
        let dist = space.distanceTo(SelectedPiece.frame.origin)
        if closestDist != nil {
            if dist < closestDist {
                ClosestDist = dist
                ClosestIndex = spaces.index(of:space)
            }
        }else {
            ClosestDist = dist
            ClosestIndex = spaces.index(of:space)
        }
    }
    if ClosestDist! < 15 {
        SelectedPiece.frame.origin = spaces[ClosestIndex]
    }
}

这显然是不完整的,但我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多