MagnifierView.h
#import <UIKit/UIKit.h>
@interface MagnifierView : UIView {
// CGPoint touchPoint;
}
@property (nonatomic, strong) UIView *viewToMagnify;
@property (nonatomic, assign) CGPoint touchPoint;
- (void)drawRect:(CGRect)rect;
@end
MagnifierView.m
#import "MagnifierView.h"
@implementation MagnifierView
- (void)setTouchPoint:(CGPoint)pt {
_touchPoint = pt;
self.center = CGPointMake(pt.x, pt.y-50);//跟随touchmove 不断得到中心点
}
- (void)drawRect:(CGRect)rect {
//绘制放大镜效果部分
CGContextRef context = UIGraphicsGetCurrentContext();//获取的是当前view的图形上下文
CGContextTranslateCTM(context,1*(self.frame.size.width*0.5),1*(self.frame.size.height*0.5 + 50));//重新设置坐标系原点
CGContextScaleCTM(context, 1.5, 1.5);//通过调用CGContextScaleCTM函数来指定x, y缩放因子 这里我们是扩大1.5倍
CGContextTranslateCTM(context,-1*(_touchPoint.x),-1*(_touchPoint.y));
[self.viewToMagnify.layer renderInContext:context];//直接在一个 Core Graphics 上下文中绘制放大后的图像,实现放大镜效果
}
@end
///
MagnifierView的使用
#import "ViewController.h"
#import "MagnifierView.h"
@interface ViewController () {
MagnifierView *loop;
}
@property (nonatomic, strong) NSTimer *touchTimer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//计时器,手指点中0.5秒后启动放大镜效果
self.touchTimer = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self
selector:@selector(addLoop)
userInfo:nil
repeats:NO];
if(loop == nil){
loop = [[MagnifierView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
loop.viewToMagnify = self.view;
loop.layer.borderColor = [UIColor grayColor].CGColor;
loop.layer.borderWidth = 2;
loop.layer.cornerRadius = 50;
loop.layer.masksToBounds = YES;
}
UITouch *touch = [touches anyObject];
loop.touchPoint = [touch locationInView:self.view];
[loop setNeedsDisplay];
[self.view addSubview:loop];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
//将手指移动信息传出给 handleAction
[self handleAction:touches];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
//手指抬起,将loop(放大镜)去掉
[self.touchTimer invalidate];
self.touchTimer = nil;
[loop removeFromSuperview];
loop = nil;
}
- (void)addLoop {
[loop bringSubviewToFront:self.view];//让放大镜显示在最上层
}
- (void)handleAction:(id)timerObj {
NSSet *touches = timerObj;
UITouch *touch = [touches anyObject];
loop.touchPoint = [touch locationInView:self.view];//将本身的touch信息传递给放大镜,设置放大镜的中心点
[loop setNeedsDisplay];
// loop drawRect:<#(CGRect)#>
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end