2011年12月20日 星期二

Gestures and View Transform

To use the UIGestureRecognizer for pinch and rotate gesture,
we first create it:
// Create a rotation gesture
UIRotationGestureRecognizer *rotate = [[UIRotationGestureRecognizer alloc]
initWithTarget:self
action:@selector(handleRotateEvent:)];
[rotate setDelegate:self];
[redBox addGestureRecognizer:rotate];
Then write the handleRotateEvent: method: // Called when the rotate gesture is recognized
- (void)handleRotateEvent:(UIRotationGestureRecognizer*)rotateGesture
{
// If our gesture ended, reset the box
if([rotateGesture state] == UIGestureRecognizerStateEnded) {
[self resetBox];
}
else {
// Store the value of our rotation gesture, then
// call our central update box tranform method
// Update box transform will also apply any transforms by the pinch gesture
rotation = rotateGesture.rotation;
[self updateBoxTransform];
}
}
In the updateBoxTransform, we directly use the rotation value to view’s transform: - (void)updateBoxTransform
{
// Create a new transform based on the scale (scale determined by pinch gesture)
CGAffineTransform transform = CGAffineTransformMakeScale(scale, scale);

// Rotate the transform based on the rotation gesture value
transform = CGAffineTransformRotate(transform, rotation);
//-- contineously using the gesture's rotation
// Apply the transform to our red box
redBox.transform = transform;
}
Here we initialize a transform with Identity and scale, each time.
The following paragraph uses another approach for the rotation:


   - (void)handleRotateEvent:(UIRotationGestureRecognizer *)gestureRecognizer
{
[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan ||
[gestureRecognizer state] == UIGestureRecognizerStateChanged) {
[gestureRecognizer view].transform =
CGAffineTransformRotate( [ [gestureRecognizer view] transform], [gestureRecognize rotation] );
[gestureRecognizer setRotation:0]; //-- reset gesture's rotation
}
}
Since the source of transform is from the view object, we have to [gestureRecognizer setRotation:0]; such that we provide a fresh rotation quantum and add to the view’s transform