2010-06-15 95 views
1

我現有的代碼用於跟蹤多點觸摸位置,然後適當地移動,旋轉和縮放項目 - 在本例中爲圖像 - 。iPhone多點觸摸移動,縮放和旋轉,如何防止縮放?

該代碼工作得很好,本身就是完美的,但是對於這個特殊任務,我只需要移動和旋轉。我花了一些時間來研究這個例程中發生了什麼,但是數學不是我的強項,所以想要看看有沒有人可以提供幫助?

- (CGAffineTransform)incrementalTransformWithTouches:(NSSet *)touches 
{ 
    NSArray *sortedTouches = [[touches allObjects] sortedArrayUsingSelector:@selector(compareAddress:)]; 
    NSInteger numTouches = [sortedTouches count]; 

// No touches 
if (numTouches == 0) { 
     return CGAffineTransformIdentity; 
    } 

// Single touch 
if (numTouches == 1) { 
     UITouch *touch = [sortedTouches objectAtIndex:0]; 
     CGPoint beginPoint = *(CGPoint *)CFDictionaryGetValue(touchBeginPoints, touch); 
     CGPoint currentPoint = [touch locationInView:self.superview]; 
    return CGAffineTransformMakeTranslation(currentPoint.x - beginPoint.x, currentPoint.y - beginPoint.y); 
} 

// If two or more touches, go with the first two (sorted by address) 
UITouch *touch1 = [sortedTouches objectAtIndex:0]; 
UITouch *touch2 = [sortedTouches objectAtIndex:1]; 

    CGPoint beginPoint1 = *(CGPoint *)CFDictionaryGetValue(touchBeginPoints, touch1); 
    CGPoint currentPoint1 = [touch1 locationInView:self.superview]; 
    CGPoint beginPoint2 = *(CGPoint *)CFDictionaryGetValue(touchBeginPoints, touch2); 
    CGPoint currentPoint2 = [touch2 locationInView:self.superview]; 

double layerX = self.center.x; 
double layerY = self.center.y; 

double x1 = beginPoint1.x - layerX; 
double y1 = beginPoint1.y - layerY; 
double x2 = beginPoint2.x - layerX; 
double y2 = beginPoint2.y - layerY; 
double x3 = currentPoint1.x - layerX; 
double y3 = currentPoint1.y - layerY; 
double x4 = currentPoint2.x - layerX; 
double y4 = currentPoint2.y - layerY; 

// Solve the system: 
// [a b t1, -b a t2, 0 0 1] * [x1, y1, 1] = [x3, y3, 1] 
// [a b t1, -b a t2, 0 0 1] * [x2, y2, 1] = [x4, y4, 1] 

double D = (y1-y2)*(y1-y2) + (x1-x2)*(x1-x2); 
if (D < 0.1) { 
     return CGAffineTransformMakeTranslation(x3-x1, y3-y1); 
    } 

double a = (y1-y2)*(y3-y4) + (x1-x2)*(x3-x4); 
double b = (y1-y2)*(x3-x4) - (x1-x2)*(y3-y4); 
double tx = (y1*x2 - x1*y2)*(y4-y3) - (x1*x2 + y1*y2)*(x3+x4) + x3*(y2*y2 + x2*x2) + x4*(y1*y1 + x1*x1); 
double ty = (x1*x2 + y1*y2)*(-y4-y3) + (y1*x2 - x1*y2)*(x3-x4) + y3*(y2*y2 + x2*x2) + y4*(y1*y1 + x1*x1); 

return CGAffineTransformMake(a/D, -b/D, b/D, a/D, tx/D, ty/D); 
} 

我已經嘗試瞭解矩陣的工作方式,但不能完全弄明白。更可能是這個問題是計算,這是我提到的不是我的強項。

我從這個例程中需要的是一個執行我的移動和旋轉但忽略縮放的變換 - 因此忽略兩個手指觸點之間的距離並且縮放不受影響。

我看過其他例程在互聯網上處理多點觸摸旋轉,但所有我試過的方式有問題以某種方式或其他(平滑,跳起時,手指等),而上述代碼是現貨移動,縮放和旋轉動作。

任何幫助表示讚賞!

回答

0

做這樣的事情:

CGAffineTransform transform = self.view.transform; 
float scale = sqrt(transform.a*transform.a + transform.c*transform.c); 
self.view.transform = CGAffineTransformScale(transform, 1/scale, 1/scale); 

在你touchesMoved結束:withEvent:方法和updateOriginalTransformForTouches方法。基本上,您可以計算當前比例值,然後將您的變換矩陣與反比例值相乘。