您的位置:首页 > 移动开发 > IOS开发

要缩小通过两个触摸点的观点(iOS)

2015-10-13 15:40 190 查看
于AppDelegate.m档,创建一个视图控制器

#import "MAYAppDelegate.h"

#import "MAYViewController.h"

@implementation MAYAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

// Override point for customization after application launch.

MAYViewController *root = [[MAYViewController alloc] init];

self.window.rootViewController = root;

[root release];

self.window.backgroundColor = [UIColor whiteColor];

[self.window makeKeyAndVisible];

return YES;

}

创建一个视图控制器MAYViewController,在视图控制器MAYViewController.m文件里,创建一个视图

#import "MAYViewController.h"

#import "Touch.h"

@interface MAYViewController ()

@end

@implementation MAYViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

if (self) {

// Custom initialization

}

return self;

}

- (void)viewDidLoad

{

[super viewDidLoad];

// Do any additional setup after loading the view.

self.view.backgroundColor = [UIColor lightGrayColor];

Touch *touch = [[Touch alloc] initWithFrame:CGRectMake(50, 150, 200, 200)];

touch.backgroundColor = [UIColor greenColor];

[self.view addSubview:touch];

[touch release];

}

新建一个视图类Touch,加入在视图控制器上,在Touch.m文件里实现缩放功能

#import "Touch.h"

@implementation Touch

- (id)initWithFrame:(CGRect)frame

{

self = [super initWithFrame:frame];

if (self) {

// Initialization code

//设置是否支持多点触摸(YES支持,NO不支持)

self.multipleTouchEnabled = YES;

}

return self;

}

//计算两点之间的距离

- (CGFloat)distance:(CGPoint)point1 point2:(CGPoint)point2

{

CGFloat dx = point1.x - point2.x;

CGFloat dy = point1.y - point2.y;

CGFloat tance = sqrt(pow(dx, 2) + pow(dy, 2));

return tance;

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event

{

if (1 == [touches count]) {

return;

}

//设置触摸点

NSArray *array = [touches allObjects];

UITouch *touch1 = [array firstObject];

UITouch *touch2 = [array lastObject];

//获取移动前的触摸点

CGPoint firstPreviousPoint = [touch1 previousLocationInView:self];

CGPoint secondPreviousPoint = [touch2 previousLocationInView:self];

//获取与移动后的触摸点

CGPoint firstCurrentPoint = [touch1 locationInView:self];

CGPoint secondCurrentPoint = [touch2 locationInView:self];

//获取移动前后的两点之间的距离

CGFloat previousDistance = [self distance:firstPreviousPoint point2:secondPreviousPoint];

CGFloat currentDistance = [self distance:firstCurrentPoint point2:secondCurrentPoint];

//获取缩放比例

CGFloat scanl = currentDistance / previousDistance;

//获得缩放后的视图大小

self.bounds = CGRectMake(0, 0, self.bounds.size.width * scanl, self.bounds.size.height * scanl);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: