iOS 截圖總結
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); }
截圖就做完了
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!