本文實例引見了IOS手動剪裁圖片並保留到相冊的具體代碼,分享給年夜家供年夜家參考,詳細內容以下
1、完成後果
1、操作步調
2、後果圖

2、完成思緒
1、在掌握器的view上添加一個imageView,設置圖片
2、在掌握器的view上添加一個pan手勢
3、跟蹤pan手勢,繪制一個矩形框(圖片的剪切區域)
4、在pan手勢停止時,經由過程alertView提醒“能否將圖片保留至相冊?”
3、完成步調
1、經由過程storyboard在掌握器的view上添加一個imageView(設置圖片),並在掌握器的.m文件中具有該屬性
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
2、設置經由過程手勢繪制的圖片的剪切區域
將圖片的剪切區域作為成員屬性clipView
@property (nonatomic, weak) UIView *clipView;
3、經由過程懶加載的方法創立clipView,並初始化
- (UIView *)clipView
{
//假如clipView為被創立,就創立
if (_clipView == nil)
{
UIView *view = [[UIView alloc] init];
_clipView = view;
//設置clipView的配景色和通明度
view.backgroundColor = [UIColor blackColor];
view.alpha = 0.5;
//將clipView添加到掌握器的view上,此時的clipView不會顯示(未設置其frame)
[self.view addSubview:_clipView];
}
return _clipView;
}
4、給掌握器的view添加pan手勢,跟蹤pan手勢,繪制圖片剪切區域
1)、創立並添加手勢
/**創立手勢**/ UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithtarget:self action:@selector(pan:)]; /** *每當pan手勢的地位產生變更,就會挪用pan:辦法,並將手勢作為參數傳遞 */ /**添加手勢**/ [self.view addGestureRecognizer:pan];
2)、增長成員屬性,記載pan手勢開端的點
@property (nonatomic, assign) CGPoint startPoint;
3)、監聽手勢的挪動
- (void)pan:(UIPanGestureRecognizer *)pan
{
CGPoint endPoint = CGPointZero;
if (pan.state == UIGestureRecognizerStateBegan)
{
/**開端點擊時,記載手勢的終點**/
self.startPoint = [pan locationInView:self.view];
}
else if(pan.state == UIGestureRecognizerStateChanged)
{
/**當手勢挪動時,靜態轉變起點的值,並盤算終點與起點之間的矩形區域**/
endPoint = [pan locationInView:self.view];
//盤算矩形區域的寬高
CGFloat w = endPoint.x - self.startPoint.x;
CGFloat h = endPoint.y - self.startPoint.y;
//盤算矩形區域的frame
CGRect clipRect = CGRectMake(self.startPoint.x, self.startPoint.y, w, h);
//設置剪切區域的frame
self.clipView.frame = clipRect;
}
else if(pan.state == UIGestureRecognizerStateEnded)
{
/**若手勢停滯,將剪切區域的圖片內容繪制到圖形高低文中**/
//開啟位圖高低文
UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, 0);
//創立年夜小等於剪切區域年夜小的關閉途徑
UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.clipView.frame];
//設置超越的內容不顯示,
[path addClip];
//獲得畫圖高低文
CGContextRef context = UIGraphicsGetCurrentContext();
//將圖片襯著的高低文中
[self.imageView.layer renderInContext:context];
//獲得高低文中的圖片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//封閉位圖高低文
UIGraphicsEndImageContext();
//移除剪切區域視圖控件,並清空
[self.clipView removeFromSuperview];
self.clipView = nil;
//將圖片顯示到imageView上
self.imageView.image = image;
//經由過程alertView提醒用戶,能否將圖片保留至相冊
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"保留圖片" message:@"能否將圖片保留至相冊?" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
[alertView show];
}
}
4)、設置alertView的署理辦法,肯定能否保留圖片
- (void)alertView:(nonnull UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//若點擊了“是”,則保留圖片
if (buttonIndex == 1)
{
UIImageWriteToSavedPhotosAlbum(self.imageView.image, nil, nil, nil);
/**
* 該辦法可以設置保留終了挪用的辦法,此處未停止設置
*/
}
}
以上就是本文的全體內容,願望對年夜家的進修有所贊助。
【IOS完成手動截圖並保留】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!