IOS学习笔记41--图片的缩放(一)
图片的缩放
一: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进行等比缩放,以达到缩放的目的。
有其他见解的同学留言讨论。
补充:移动开发 , IOS ,