十一 iOS 图片截取

简单介绍截取图片

完整图片

这里写图片描述

截取后的图片
这里写图片描述

首先创建一个UIImageView,导入图片
然后ViewController.m
#import "ViewController.h"

@interface ViewController ()

@property(nonatomic,assign)CGPoint startP;

/**截取的view*/
@property(nonatomic,weak)UIView * clipView;

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

@end

@implementation ViewController
//懒加载clipView
-(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];

    //添加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) {

        //获取一开始的触摸点

        self.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(_myImageView.bounds.size, NO, 0);

        //设置裁剪区域
        UIBezierPath * path = [UIBezierPath bezierPathWithRect:self.clipView.frame];

        [path addClip];

        //获取上下文
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        //把控件上的内容渲染到上下文
        [self.myImageView.layer renderInContext:ctx];


        //生成一张新的图片
        _myImageView.image = UIGraphicsGetImageFromCurrentImageContext();

        //关闭上下文
        UIGraphicsEndPDFContext();

        //先移除
        [self.clipView removeFromSuperview];
        _clipView = nil;

    }



}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值