標籤:
移動思路:
設定一個私人屬性用來儲存一個點,在開始觸摸時記錄觸摸點的位置,在觸摸動作移動中記錄下移動到的點,求出兩個點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 視圖移動及縮放