iOS 截图总结

jopen 10年前

iOS的截图都会想到按住唤醒键加HOME键,我要说的截图是类似于QQ截图。

首先我们要绘制虚线选框:
那我们就要获取手指触摸屏幕的起始点,那我们就要用到的方法是:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

这个方法是系统为我们提供的。

在这个方法里面记录起始点完整代码如下:

      -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event    {        UITouch * touch = [touches anyObject];           point = [touch locationInView:self];//记录起始点,point是声明为全局变量         } 

记录完起始坐标后,我们做的是在我们手指移动的时候画虚线的矩形框,我们就要用到一个方法,这个方法也是系统为我们提供的:-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
完整代码如下:

 

 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event    {                UITouch *touch1=[touches anyObject];        CGPoint endPoint=[touch1 locationInView:self];//记录结束点的坐标       用结束点的坐标减去起始点的坐标我么得到一个矩形框的宽和高       声明一个点记录一下;        point2.x=endPoint.x-startPoint.x;        point2.y=endPoint.y-startPoint.y;        调用重绘方法     [self setNeedsDisplay];            } 


准备工作做好后,我们就要画虚线的矩形框了


我们需要重写drawRect方法。完整代码如下:

 

 - (void)drawRect:(CGRect)rect    {          //获取绘图上下文-画板        CGContextRef ref=UIGraphicsGetCurrentContext();        //设置虚线        CGContextSetLineDash(ref,2, dashPattern, 1);          //画截取线框      CGContextAddRect(ref,CGRectMake(startPoint.x,startPoint.y,point2.x,point2.y));          //设置颜色        CGContextSetStrokeColorWithColor(ref,[UIColor redColor].CGColor);      //设置线宽       CGContextSetLineWidth(ref,2);        CGContextStrokePath(ref);  } 


这样我们的虚线选款就做好了,现在我们要实现截图功能,
首先我们先初始化一个  UIImageView ,然后把图片贴到上面具体代码如下:
 - (id)initWithFrame:(CGRect)frame         {        self = [super initWithFrame:frame];        if (self)         {            _imageView = [[UIImageView alloc] initWithFrame:CGRectZero];            [self addSubview:_imageView];            self.backgroundColor = [UIColor colorWithPatternImage:[UIImage            imageNamed:@"iphone.jpg"]];              }        return self;    }

然后截取我们想要的图片,我们还是在drawRect方法里来实现,
 - (void)drawRect:(CGRect)rect    {       先加载一张图片到ImageView上           UIImage *image=[UIImage imageNamed:@"iphone.jpg"];           //截取图片    CGImageRef  img= CGImageCreateWithImageInRect(image.CGImage,CGRectMake(startPoint.x,startPoint.y,point2.x,point2.y));          UIImage *newImage = [UIImage imageWithCGImage:img];         _imageView.image = newImage;         _imageView.frame = CGRectMake(startPoint.x,startPoint.y,point2.x,point2.y);  } 

截图就做完了
</div> </div> </div>