Image Scaling
I. The Pinch gesture scales the image. That is, drag the photo with two fingers in different directions, and the photo will be scaled down or enlarged.
Principle I understand: proportional Scaling
Let's take a look at the following key code:
1. initialization parameters
-(Void) viewDidLoad
{
[SuperviewDidLoad];
LastDistance = 0.0;
ImageStartHeight = self. scaleImage. frame. size. height;
ImageStartWidth = self. scaleImage. frame. size. width;
}
2. Scaling operation
-(Void) touchesMoved :( NSSet *) touches withEvent :( UIEvent *) event {
CGPoint point1; // Point
CGPoint point2;
CGFloat sub_x; // X distance between two fingers
CGFloat sub_y; // Y distance between two fingers
CGFloat currentDistance; // The distance between the current two mobile phones
CGRect imageFrame; // obtain the frame of the activity range
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 (@ "zoom in ");
ImageFrame. size. width + = 10;
If (imageFrame. size. width> 1000)
{
ImageFrame. size. width = 1000;
}
LastDistance = currentDistance;
}
If (currentDistance <lastDistance-2)
{
// NSLog (@ "zoom in ");
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;
}
In fact, his key lies in: determining the distance between two fingers. When the distance is greater than a certain distance, the image frame is scaled proportionally to achieve the purpose of scaling.
If you have other opinions, leave a message for discussion.