iOS中手指拖动生成截图范围并截图

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, assign) CGPoint startP;

@property (weak, nonatomic) IBOutlet UIImageView *imageV;

@property (nonatomic, weak) UIView *clipView;

@end

@implementation ViewController

- (UIView *)clipView{

if (_clipView == nil) {

UIView *view = [[UIView alloc] init];

_clipView = view;

view.backgroundColor = [UIColor blackColor];

view.alpha = 0.5;

[self.view addSubview:view];

}

return _clipView;

}

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

// 给控制器的view添加一个pan手势

UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];

[self.view addGestureRecognizer:pan];

}

- (void)pan:(UIPanGestureRecognizer *)pan

{

CGPoint endA = CGPointZero;

if (pan.state == UIGestureRecognizerStateBegan) {

 // 一开始拖动的时候

// 获取一开始触摸点

_startP = [pan locationInView:self.view];

}else if(pan.state == UIGestureRecognizerStateChanged){ 

// 一直拖动

// 获取结束点

endA = [pan locationInView:self.view];

CGFloat w = endA.x - _startP.x;

CGFloat h = endA.y - _startP.y;

// 获取截取范围

CGRect clipRect = CGRectMake(_startP.x, _startP.y, w, h);

// 生成截屏的view

self.clipView.frame = clipRect;

}else if (pan.state == UIGestureRecognizerStateEnded){

// 图片裁剪,生成一张新的图片

// 开启上下文

// 如果不透明,默认超出裁剪区域会变成黑色,通常都是透明

UIGraphicsBeginImageContextWithOptions(_imageV.bounds.size, NO, 0);

// 设置裁剪区域

UIBezierPath *path =  [UIBezierPath bezierPathWithRect:_clipView.frame];

[path addClip];

// 获取上下文

CGContextRef ctx = UIGraphicsGetCurrentContext();

// 把控件上的内容渲染到上下文

[_imageV.layer renderInContext:ctx];

// 生成一张新的图片

_imageV.image = UIGraphicsGetImageFromCurrentImageContext();

// 关闭上下文

UIGraphicsEndImageContext();

// 先移除

[_clipView removeFromSuperview];

// 截取的view设置为nil

_clipView = nil;

}

转载于:https://www.cnblogs.com/CJH5209/p/6032718.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值