捏合视图变化(视图的缩放), 单击随着鼠标移动, 双击放大视图,再双击还原视图

来源:互联网 发布:图片裁剪软件 编辑:程序博客网 时间:2024/05/16 19:20
////  CLView.m//  Homework_UIEvent////  Created by lanouhn on 14-8-26.//  Copyright (c) 2014年 vaercly@163.com 陈聪雷. All rights reserved.//#import "CLView.h"@interface CLView ()//{//    CGPoint _firstPreviousLocation;//    CGPoint _secondPreviousLocation;//}@end@implementation CLView- (id)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {        // Initialization code        self.multipleTouchEnabled = YES;    }    return self;}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    static int i = 1;    //双击放大, 再次双击恢复    if (1 == touches.count && 2 == [[touches anyObject] tapCount]) {        if (1 == i % 2) {            self.bounds = CGRectMake(0, 0, self.bounds.size.width * 3.0, self.bounds.size.height * 3.0);        } else {            self.bounds = CGRectMake(0, 0, self.bounds.size.width / 3.0, self.bounds.size.height / 3.0);        }        i++;    }}- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{    }- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{    }- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{    //获取两个点移动之后的位置    NSArray *allTouches = [touches allObjects];    UITouch *firstTouch = [allTouches firstObject];    UITouch *secondTouch = [allTouches lastObject];        //获取两个手指之前的位置    CGPoint firstPreviousLocation = [firstTouch previousLocationInView:self];    CGPoint secondPreviousLocation = [secondTouch previousLocationInView:self];    //获取两个手指当前位置    CGPoint firstCurrentLocation = [firstTouch locationInView:self];    CGPoint secondCurrentLocation = [secondTouch locationInView:self];        //若只有一个手指触摸屏幕并移动时, view同样移动    if (1 == [touches count]) {        self.center = CGPointMake(self.center.x + firstCurrentLocation.x - firstPreviousLocation.x, self.center.y + firstCurrentLocation.y - firstPreviousLocation.y);        return;    }            //获取之前两个点的距离    CGFloat previousDistance = [self distanceOfPoint1:firstPreviousLocation point2:secondPreviousLocation];    //获取当前两个点的距离    CGFloat currentDistance = [self distanceOfPoint1:firstCurrentLocation point2:secondCurrentLocation];    //    NSLog(@"%g", previousDistance);    //求变化的比例    CGFloat scale = currentDistance / previousDistance;    //修改视图的大小, 按比例缩放    self.bounds = CGRectMake(0, 0, self.bounds.size.width * scale, self.bounds.size.height * scale);    }//计算两个点的距离- (CGFloat)distanceOfPoint1:(CGPoint)point1 point2:(CGPoint)point2{    CGFloat dx = point1.x - point2.x;    CGFloat dy = point1.y - point2.y;    return sqrt(pow(dx, 2) + pow(dy, 2));}/*// Only override drawRect: if you perform custom drawing.// An empty implementation adversely affects performance during animation.- (void)drawRect:(CGRect)rect{    // Drawing code}*/@end

0 0
原创粉丝点击