我有一个问题,
我希望黑色按钮不会移出三角形,(参见flickr链接) 如果它越过三角形的边缘,那么按钮将返回到三角形中。
我该怎么做?
link:http://www.flickr.com/photos/92202376@N08/8590549046/in/photostream
#import "DraggableViewController.h"
@interface DraggableViewController ()
@end
@implementation DraggableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// create a new button
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setBackgroundImage:[UIImage imageNamed:@"Scale9Image.png"]
forState:UIControlStateNormal];
// add drag listener
[button addTarget:self action:@selector(wasDragged:withEvent:)
forControlEvents:UIControlEventTouchDragInside];
// center and size
button.frame = CGRectMake((self.view.bounds.size.width - 100)/1.6,
(self.view.bounds.size.height - 50)/1.9,
40, 40);
button.frame.origin.y;
[self.view addSubview:button];
}
- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
{
// get the touch
UITouch *touch = [[event touchesForView:button] anyObject];
// get delta
CGPoint previousLocation = [touch previousLocationInView:button];
CGPoint location = [touch locationInView:button];
CGFloat delta_x = location.x - previousLocation.x;
CGFloat delta_y = location.y - previousLocation.y;
// move button
button.center = CGPointMake(button.center.x + delta_x,
button.center.y + delta_y);
}
@end
答案 0 :(得分:0)
查看您在-wasDragged
移动按钮的那一行?
button.center = CGPointMake(button.center.x + delta_x,
button.center.y + delta_y);
您可以通过测试新点来防止按钮离开三角形,以确保在移动按钮之前它位于三角形内部。更好的是,您可以简单地计算最接近新点的三角形内的点并使用它,因此当触摸移动到三角形之外时按钮仍将移动,但它将被约束为三角形:
CGPoint newPoint = CGPointMake(button.center.x + delta_x,
button.center.y + delta_y);
button.center = [self buttonPositionNearestToPoint:newPoint];
当然,您需要实施-buttonPositionNearestToPoint:
方法。你需要一点计算几何来做到这一点。查看Point in triangle test以获得温和的介绍。 barycentric coordinate clamping on 3d triangle也可能有用,即使它是3D而不是2D。