圖片的縮放
一:Pinch手勢對圖片進行縮放。即用兩根手指往不同方向拖拉照片,照片會被縮小或放大。
我理解的原理:等比縮放
先看如下關鍵代碼:
1.初始化參數
- (void)viewDidLoad
{
[superviewDidLoad];
lastDistance = 0.0;
imageStartHeight = self.scaleImage.frame.size.height;
imageStartWidth = self.scaleImage.frame.size.width;
}
2.縮放操作
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
CGPoint point1; //Point
CGPoint point2;
CGFloat sub_x; //兩手指間的 X距離
CGFloat sub_y;//兩手指間的 Y距離
CGFloat currentDistance; //當前兩手機間的距離
CGRect imageFrame; //獲得活動范圍的frame
NSArray *touchArray = [[event allTouches]allObjects];
if ([touchArray count] >= 2) {
point1 = [[touchArrayobjectAtIndex:0]locationInView:self.view];
point2 = [[touchArrayobjectAtIndex:1]locationInView:self.view];
sub_x = point1.x-point2.x;
sub_y = point1.y-point2.y;
currentDistance =sqrtf(sub_x * sub_x + sub_y * sub_y);
if (lastDistance >0)
{
imageFrame =self.scaleImage.frame;
if (currentDistance > lastDistance +2)
{
// NSLog(@"放大");
imageFrame.size.width +=10;
if (imageFrame.size.width >1000)
{
imageFrame.size.width =1000;
}
lastDistance = currentDistance;
}
if (currentDistance < lastDistance -2)
{
// NSLog(@"縮小");
imageFrame.size.width -=10;
if (imageFrame.size.width <50)
{
imageFrame.size.width =50;
}
lastDistance = currentDistance;
}
NSLog(@"currentDistance :%f lastDistance : %f",currentDistance,lastDistance);
if (currentDistance == lastDistance) {
imageFrame.size.height =imageStartHeight*imageFrame.size.width/imageStartWidth;
float addwidth = imageFrame.size.width -self.scaleImage.frame.size.width;
float addheight = imageFrame.size.height -self.scaleImage.frame.size.height;
self.scaleImage.frame =CGRectMake(imageFrame.origin.x - addwidth/2.0f, imageFrame.origin.y - addheight/2.0f, imageFrame.size.width, imageFrame.size.height);
}
}
else{
lastDistance = currentDistance;
}
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
lastDistance = 0;
}
其實他的關鍵所在就在於:判斷兩手指間的距離,當大於一定的距離的時候就對圖片的frame進行等比縮放,以達到縮放的目的。
有其他見解的同學留言討論。