0

我希望黑色按钮不要移出三角形(请参阅 Flickr 链接),如果它越过三角形的边缘,则该按钮将返回到三角形中。

我怎么做?

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
4

1 回答 1

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以获得温和的介绍。3d 三角形上的重心坐标钳制也可能很有帮助,即使它是 3D 而不是 2D。

于 2013-03-25T20:22:36.457 回答