这应该这样做。保存拖动的开始位置,获取每个移动事件的当前位置。将它们传递给这个函数。它将回答一个可以应用于按钮框架的向量。
计算的要点是通过选择阻力的最小分量(x 或 y)并回答在两个维度上具有相同大小的向量(保留两个轴上的符号)来确定大小。
// answer a vector to apply to an object's frame, constrained to a diagonal
- (CGPoint)constrainToDiagonalFrom:(CGPoint)from to:(CGPoint)to {
CGPoint diff = CGPointMake(to.x-from.x, to.y-from.y);
CGFloat magnitude = MIN(fabs(diff.x), fabs(diff.y)); // this is how large the drag will be
return CGPointMake(copysignf(magnitude, diff.x), copysignf(magnitude, diff.y));
}
像这样称呼它:
// on touches moved
// we saved startPoint on touches began
// get location from this event's touches
CGPoint diagonal = [self constrainToDiagonalFrom:startPoint to:location];
myButton.frame = CGRectOffset(myButton.frame, diagonal.x, diagonal.y);
您可以随意计算幅度。最大分量,最小分量,平均值等。只要结果在两个维度上都是对称的。