码迷,mamicode.com
首页 > 移动开发 > 详细

iOS UI 视图移动及缩放

时间:2015-08-16 21:21:41      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

移动思路:

      设置一个私有属性用来存储一个点,在开始触摸时记录触摸点的位置,在触摸动作移动中记录下移动到的点,求出两个点X轴Y轴的变化量,将原视图的中心点B赋值给新点,将新点得X,Y 加上变化量的到新点A,在将A赋给B,,经过中心点的变化来移动视图

@interface YDview ()

@property (nonatomic, assign)CGPoint beginPoint;
@end

@implementation YDview

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch * touch = [touches anyObject];
    self.beginPoint = [touch locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch * touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    CGFloat changeX = point.x - self.beginPoint.x;
    CGFloat changeY = point.y - self.beginPoint.y;
    CGPoint center = self.center;
    center.x += changeX;
    center.y += changeY;
    self.center = center;

    
}

@end

 

 

 

缩放思路:

需要先开启多点触摸(默认是关闭的)

求出视图的缩放比例A后,将视图的bounts * A 得到新的bounds,有bounds 的改变来控制视图;(这里不能利用frame,原因我说不清(左上角不会变),哪位能说清的麻烦告诉我下)

求出视图的缩放比例A:定义私有属性存放两点(两个手指的)之间的距离. 新距离与旧距离的比例就是视图缩放比例(两手指缩放前后改变的比例)

#import "SuofangView.h"

@interface SuofangView ()
@property (nonatomic, assign)CGFloat beginDistance;
@end
@implementation SuofangView

- (instancetype)initWithFrame:(CGRect)frame

{
    self = [super initWithFrame:frame];
    if (self) {
        self.multipleTouchEnabled = YES;//需要先开启多点触摸
    }
    return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch * touch1 = [[touches allObjects] lastObject];//)touches 是集合类型
    UITouch * touch2 = [[touches allObjects] firstObject];
    CGPoint p1 = [touch1 locationInView:self];
    CGPoint p2 = [touch2 locationInView:self];
    self.beginDistance = [self getDistance:p1 p2:p2];
}

- (CGFloat)getDistance:(CGPoint)p1
                    p2:(CGPoint)p2//求两点距离
{
    return sqrt(pow((p1.x - p2.x), 2) + pow(p1.y - p2.y, 2));
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch * touch1 = [[touches allObjects] lastObject];
    UITouch * touch2 = [[touches allObjects] firstObject];
    CGPoint p1 = [touch1 locationInView:self];
    CGPoint p2 = [touch2 locationInView:self];
    CGFloat distance = [self getDistance:p1 p2:p2];
    
    CGFloat scale = distance / self.beginDistance;
    CGRect newbount = self.bounds;
    newbount.size.height *= scale;
    newbount.size.width *= scale;
    self.bounds = newbount;//把新bounds赋值给self.bounds
    self.beginDistance = distance;//将新距离赋给self.beginDistance,没有这句的话,缩放比例会有误的,自己试试(被除数永远不会变..)
}
@end

iOS UI 视图移动及缩放

标签:

原文地址:http://www.cnblogs.com/lzcdbk/p/4734938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!