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」が 2 回呼び出され、subView と 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
これはなぜですか?