我使用 UIBezierPath 实现了一个正方形绘制。为了移动同一个方块,我实现了一个 UILongPressGestureRecognizer 以便我可以检查方块是否被按下并在子视图中自由移动方块。
这是一些代码:
square.h
...
//square coordinates and size
static const float xPoint = 10;
static const float yPoint = 16;
static const float Width = 10;
static const float Height = 20;
//bezier BitMap context
static const float contextWidht = 300;
static const float contextHeigh = 300;
...
square.m
...
-(void)build{
UIBezierPath *squareDraw = [UIBezierPath bezierPathWithRect:CGRectMake(xPoint, yPoint, Width, Height)];
UIGraphicsBeginImageContext(CGSizeMake(contextWidht, contextHeigh));
// Graphic Context
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
[squareDraw fill];
[squareDraw stroke];
// Get image from Graphic Context
UIImage *bezierImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageView *bezierImageView = [[UIImageView alloc]initWithImage:bezierImage];
//subView
_frame = bezierImageView;
[_frame setUserInteractionEnabled:YES];
//Gesture Recognizer
UILongPressGestureRecognizer *tapGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandler:)];
tapGesture.delegate = (id)self;
[_frame addGestureRecognizer:tapGesture];
[self addSubview:_frame];
}
- (void)tapHandler:(UILongPressGestureRecognizer *) sender{
sender.delegate = (id)_frame;
CGPoint touchLocation = [sender locationInView:_frame];
CGFloat xVariation, yVariation;
...
case UIGestureRecognizerStateChanged:
xVariation = [sender locationInView:_frame].x;
yVariation = [sender locationInView:_frame].y;
_frame.center = CGPointMake(xVariation, yVariation);
break;
....
}
似乎,在调试应用程序时(按下并移动 _frame),“UIGestureRecognizerStateChanged”被调用两次,并返回子视图和由 contextWidth 和 contextHeight 产生的一些点之间的交替点:
2013-07-22 14:55:00.327 bezier[10847:11603] xVariation: 22.000000
2013-07-22 14:55:00.329 bezier[10847:11603] yVariation: 28.000000
2013-07-22 14:55:00.330 bezier[10847:11603] xVariation: 150.000000 ----> ??
2013-07-22 14:55:00.330 bezier[10847:11603] yVariation: 150.000000 ----> ??
2013-07-22 14:55:00.332 bezier[10847:11603] xVariation: 29.000000
2013-07-22 14:55:00.332 bezier[10847:11603] yVariation: 28.000000
为什么会这样?