iOS 裁剪工具

来源:https://www.cnblogs.com/chao8888/archive/2019/11/29/11958988.html
-Advertisement-
Play Games

下載 "demo和工具下載鏈接SPClipTool" 使用說明 需求 圖片裁剪,效果如下圖,支持圖片拖拽,縮放,裁剪框自由變換大小。 思路 兩個UIImageView,一個做背景,並加上蒙版效果,另外一個通過蒙版控制顯示區域,並且保證兩個UIImageView平移和縮放的時候完全重疊。最後使用一個U ...


下載

demo和工具下載鏈接SPClipTool

使用說明

[[SPClipTool shareClipTool] sp_clipOriginImage:pickerImage complete:^(UIImage * _Nonnull image) {
    // 獲取到裁剪後的image 後續操作
}];

需求

圖片裁剪,效果如下圖,支持圖片拖拽,縮放,裁剪框自由變換大小。

思路

兩個UIImageView,一個做背景,並加上蒙版效果,另外一個通過蒙版控制顯示區域,並且保證兩個UIImageView平移和縮放的時候完全重疊。最後使用一個UIView來做交互,繪製三分網格線(專業術語我不知道叫啥,截圖時一個參照,2/3 ≈0.667 接近黃金比0.618)。

註意

  • 坐標系轉換問題。
  • mask靈活使用問題。
  • 手勢的處理和三分網格線繪製的時候,計算線條寬度和長度需要特別註意。

  • 為了增強用戶體驗,在裁剪框邊緣交互設計的時候,註意額外增加用戶的可操控範圍。

實現

  • 初始化兩個UIImageView,一個做背景圖(backgroudImageView),一個用來顯示裁剪區域(clipImageView),拖拽手勢加到了clipImageView。
- (void)setupImageView {
    // backgroudImageView 
    UIImageView *backgroudImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    backgroudImageView.contentMode = UIViewContentModeScaleAspectFit;
    backgroudImageView.image = self.originImage;
    [self.view addSubview:backgroudImageView];
    self.backgroudImageView = backgroudImageView;
    backgroudImageView.layer.mask = [[CALayer alloc] init];
    backgroudImageView.layer.mask.frame = backgroudImageView.bounds;
    backgroudImageView.layer.mask.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5].CGColor;
    
    // clipImageView
    UIImageView *clipImageView = [[UIImageView alloc] initWithFrame:backgroudImageView.frame];
    clipImageView.userInteractionEnabled = YES;
    clipImageView.image = backgroudImageView.image;
    clipImageView.contentMode = backgroudImageView.contentMode;
    [self.view addSubview:clipImageView];
    self.clipImageView = clipImageView;
    clipImageView.layer.mask = [[CALayer alloc] init];
    clipImageView.layer.mask.backgroundColor = [UIColor whiteColor].CGColor;
    clipImageView.layer.mask.borderColor = [UIColor whiteColor].CGColor;
    clipImageView.layer.mask.borderWidth = 1;
    [clipImageView.layer.mask removeAllAnimations];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(imagePan:)];
    [clipImageView addGestureRecognizer:panGesture];
}
  • 初始化用於裁剪交互的SPClipView
- (void)setupClipView {
    SPClipView *clipView = [[SPClipView alloc] init];
    clipView.backgroundColor = [UIColor clearColor];
    // 打開下麵兩行註釋,可以查看真實clipView的大小。
//    clipView.layer.borderColor = [UIColor whiteColor].CGColor;
//    clipView.layer.borderWidth = 1;
    [self.view addSubview:clipView];
    self.clipView = clipView;
    // 獲取真實frame
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        clipView.frame = CGRectMake(0, 0, self.view.width / 1.5, self.view.height / 1.5);
          clipView.center = self.view.center;
        self.backgroudImageView.frame = self.view.bounds;
        self.clipImageView.frame = self.backgroudImageView.frame;
        [self dealMask];
    });

    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(clipPan:)];
    [clipView addGestureRecognizer:panGesture];
    
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGestureAction:)];
    [self.view addGestureRecognizer:pinchGesture];
}
  • 手勢處理
#pragma mark- UIPanGestureRecognizer
- (void)clipPan:(UIPanGestureRecognizer *)panGesture {
    CGPoint point = [panGesture translationInView:self.clipView];
    self.clipView.origin = [self.clipView convertPoint:point toView:self.view];
    [self expandClipView:panGesture];
    [self dealGuideLine:panGesture];
    [self dealMask];
    [panGesture setTranslation:CGPointMake(0, 0) inView:self.view];
}

- (void)imagePan:(UIPanGestureRecognizer *)panGesture {
    CGPoint point = [panGesture translationInView:self.clipImageView];
    self.clipImageView.origin = [self.clipImageView convertPoint:point toView:self.view];
    self.backgroudImageView.center = self.clipImageView.center;
    [self dealGuideLine:panGesture];
    [self dealMask];
    [panGesture setTranslation:CGPointMake(0, 0) inView:self.view];
}

#pragma mark- UIPinchGestureRecognizer
- (void)pinchGestureAction:(UIPinchGestureRecognizer *)pinchGesture {
    switch (pinchGesture.state) {
        case UIGestureRecognizerStateBegan: {
            if (lastScale <= minScale) {
                lastScale = minScale;
            }else if (lastScale >= maxScale) {
                lastScale = maxScale;
            }
            self.clipImageViewCenter = self.clipImageView.center;
            self.clipView.showGuideLine = YES;
        }
        case UIGestureRecognizerStateChanged: {
            CGFloat currentScale = lastScale + pinchGesture.scale - 1;
            if (currentScale > minScale && currentScale < maxScale) {
                [self dealViewScale:currentScale];
            }
        }
            break;
        case UIGestureRecognizerStateEnded:
            lastScale += (pinchGesture.scale - 1);
            self.clipView.showGuideLine = NO;
            [self.clipView setNeedsDisplay];
        default:
            break;
    }
}

#pragma mark- Action
- (void)dealViewScale:(CGFloat)currentScale {
    self.clipImageView.width = currentScale * self.view.width;
    self.clipImageView.height = currentScale * self.view.height;
    self.clipImageView.center = self.clipImageViewCenter;
    self.backgroudImageView.frame = self.clipImageView.frame;
    self.backgroudImageView.layer.mask.frame = self.backgroudImageView.bounds;
    [self.backgroudImageView.layer.mask removeAllAnimations];
    [self dealMask];
}

- (void)expandClipView:(UIPanGestureRecognizer *)panGesture {
    CGPoint point = [panGesture translationInView:self.clipImageView];
    CGFloat margin = 60;
    CGFloat minValue = margin;
    if (panGesture.numberOfTouches) {
        CGPoint location = [panGesture locationOfTouch:0 inView:panGesture.view];
        if (location.x < margin) {
            self.clipView.width = MAX(self.clipView.width -= point.x, minValue);
        }
        if ((self.clipView.width - location.x) < margin) {
            self.clipView.frame = CGRectMake(self.clipView.x - point.x, self.clipView.y, self.clipView.width + point.x, self.clipView.height);
        }
        if (location.y < margin) {
            self.clipView.height = MAX(self.clipView.height -= point.y, minValue);
        }
        if ((self.clipView.height - location.y) < margin) {
            self.clipView.frame = CGRectMake(self.clipView.x , self.clipView.y - point.y, self.clipView.width, self.clipView.height + point.y);
        }
    }
}

- (void)dealGuideLine:(UIPanGestureRecognizer *)panGesture  {
    switch (panGesture.state) {
        case UIGestureRecognizerStateBegan:
            self.clipView.showGuideLine = YES;
            break;
        case UIGestureRecognizerStateEnded:
            self.clipView.showGuideLine = NO;
            break;
        default:
            break;
    }
}

- (void)dealMask {
    // 額外增加拖拉區域 增強邊緣手勢體驗
    CGFloat margin = 30;
    CGRect rect = [self.view convertRect:self.clipView.frame toView:self.clipImageView];
    self.clipImageView.layer.mask.frame = CGRectMake(rect.origin.x + margin, rect.origin.y + margin, rect.size.width - 2 * margin, rect.size.height - 2 * margin);
    [self.clipView setNeedsDisplay];
    [self.clipImageView.layer.mask removeAllAnimations];
}
  • 圖片裁剪
- (void)clipImage {
    
    CGSize size = self.view.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    [self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:NO];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGImageRef cgImage = [image CGImage];
    CGRect rect = [self.clipImageView convertRect:self.clipImageView.layer.mask.frame toView:self.view];
    
    // 邊框線條寬度值
    CGFloat borderW = 1;
    CGImageRef cgClipImage = CGImageCreateWithImageInRect(cgImage, CGRectMake((rect.origin.x + borderW / 2) * image.scale, (rect.origin.y + borderW / 2) * image.scale, (rect.size.width - borderW) * image.scale, (rect.size.height - borderW) * image.scale));
    UIGraphicsEndImageContext();
    if (self.complete) {
        self.complete([UIImage imageWithCGImage:cgClipImage]);

    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
  • 裁剪區域繪製

    在這裡,裁剪區域的矩形框我並沒有直接採用clipView的fram大小,而是在其內部繪製了一個矩形框,為了讓用戶在調節邊緣的時候更靈活,不然只有當手指在邊框內部邊緣才能觸發調節邊框大小的事件。如下圖,可以看到clipView真實的大小(外框)。

@implementation SPClipView

- (void)drawRect:(CGRect)rect {
    // Drawing code
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(currentContext, [UIColor whiteColor].CGColor);
    CGContextSetLineWidth(currentContext, 1);
    // 額外增加拖拉區域 增強邊緣手勢體驗,該值應該和上文- (void)dealMask;方法中的margin一致
    CGFloat margin = 30;
  
    // 繪製矩形框
    CGContextAddRect(currentContext, CGRectMake(margin, margin, self.width - 2 * margin, self.height - 2 * margin));
    CGContextStrokePath(currentContext);
    
    // 繪製三分線
    CGFloat maskW = self.width - 2 * margin;
    CGFloat maskH = self.height - 2 * margin;
    CGContextSetLineWidth(currentContext, 0.5);
    if (self.showGuideLine) {
        CGContextSetStrokeColorWithColor(currentContext, [UIColor whiteColor].CGColor);
    }else {
        CGContextSetStrokeColorWithColor(currentContext, [UIColor clearColor].CGColor);
    }
    CGContextMoveToPoint(currentContext, margin, maskH / 3 + margin);
    CGContextAddLineToPoint(currentContext, self.width - margin, maskH / 3 + margin);
    CGContextMoveToPoint(currentContext, margin, 2 / 3.0 * maskH + margin);
    CGContextAddLineToPoint(currentContext, self.width - margin, 2 / 3.0 * maskH + margin);
    
    CGContextMoveToPoint(currentContext, maskW / 3 + margin, margin);
    CGContextAddLineToPoint(currentContext, maskW  / 3+ margin, self.height - margin);
    CGContextMoveToPoint(currentContext, 2 / 3.0 * maskW + margin, margin);
    CGContextAddLineToPoint(currentContext, 2 / 3.0 * maskW + margin, self.height - margin);
    
    CGContextStrokePath(currentContext);
    
    // 繪製四角
    CGFloat cornerL = 15;
    CGFloat cornerLW = 2;
    // 實際的長度
    CGFloat cornerRL = cornerL + cornerLW;
    CGPoint originH = CGPointMake(margin - cornerLW, margin - cornerLW / 2);
    CGPoint originV = CGPointMake(margin - cornerLW / 2, margin - cornerLW);
    CGContextSetStrokeColorWithColor(currentContext, [UIColor whiteColor].CGColor);
    CGContextSetLineWidth(currentContext, cornerLW);
    
    // 左上
    CGContextMoveToPoint(currentContext, originH.x, originH.y);
    CGContextAddLineToPoint(currentContext, originH.x + cornerRL, originH.y);
    CGContextMoveToPoint(currentContext, originV.x, originV.y);
    CGContextAddLineToPoint(currentContext, originV.x, originV.y + cornerRL);
    
    // 左下
    CGContextMoveToPoint(currentContext, originH.x, originH.y + maskH + cornerLW);
    CGContextAddLineToPoint(currentContext, originH.x + cornerRL, originH.y + maskH + cornerLW);
    CGContextMoveToPoint(currentContext, originV.x, originV.y + maskH + 2 * cornerLW);
    CGContextAddLineToPoint(currentContext, originV.x, originV.y + maskH + 2 * cornerLW - cornerRL);
    
    // 右上
    CGContextMoveToPoint(currentContext, originH.x + maskW + 2 * cornerLW, originH.y);
    CGContextAddLineToPoint(currentContext, originH.x + maskW + 2 * cornerLW - cornerRL, originH.y);
    CGContextMoveToPoint(currentContext, originV.x + maskW + cornerLW, originV.y);
    CGContextAddLineToPoint(currentContext, originV.x + maskW + cornerLW, originV.y + cornerRL);
    
    // 右下
    CGContextMoveToPoint(currentContext, originH.x + maskW + 2 * cornerLW, originH.y + maskH + cornerLW);
    CGContextAddLineToPoint(currentContext, originH.x + maskW + 2 * cornerLW - cornerRL, originH.y + maskH + cornerLW);
    CGContextMoveToPoint(currentContext, originV.x + maskW + cornerLW, originV.y + maskH + 2 * cornerLW);
    CGContextAddLineToPoint(currentContext, originV.x + maskW + cornerLW, originV.y + maskH + 2 * cornerLW - cornerRL);

    CGContextStrokePath(currentContext);
}

這裡一定要註意線條的寬度,線條是有寬度的,繪製路徑位於線條的中心位置。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、官網地址 https://studio3t.com/ 二、下載和安裝 點擊DOWNLOAD即可下載 按照自己電腦系統進行選擇,然後填寫郵箱和選擇行業,第一次登錄如果不提交不會下載,下載完成是一個zip壓縮包(我的電腦是windows系統),解壓縮安裝即可,安裝途中可以自行選擇安裝路徑 安裝完成選 ...
  • 使用SQL語句修改Mysql資料庫字元集的方法 修改庫: alter database [$database] character set [$character_set] collate [$collation_name] 註:[$database]為資料庫的庫名。[$character_set] ...
  • 2019年8月5日18:39:06 10.20.100.21rootbayaim 01-Docker介紹 docker -- go 語言編寫一次運算,到處運行只能 運行在linux 64位系統 docker 組成: (後臺進程) 1.鏡像(image) 2.容器(container) 3.倉庫(re ...
  • mysqladmin是一個執行管理操作的客戶端程式。它可以用來檢查伺服器的配置和當前狀態、創建和刪除資料庫等。 mysqladmin工具的使用格式:mysqladmin [option] command [command option] command ...... 1.查看mysql的安裝目錄,進 ...
  • #菜鳥教程地址https://www.runoob.com/docker/docker-tutorial.html#docker官方地址倉庫https://hub.docker.com/ docker 安裝 1.更新內核yum update2.下載安裝腳本curl -fsSL https://get ...
  • 項目是一個即時聊天的社交軟體,聊天流採用的是UICollectionView,隨著進度的完善,發現一個特別的bug,UICollectionviewCell的復用,並沒有直接insert進去,而是出現了莫名奇妙的插入方式, 這不是我的圖,這是我在網上找到的,跟我的效果一樣一樣的。link the i ...
  • 寫這篇文章的原因 在移動端一般很少使用複雜的表單,一般針對於屬性的更改都會打開一個新的頁面進行更改。雖然不多,但是也會有。如果一個頁面要輸入的內容包括姓名、地址、郵箱、手機號等,對各個屬性的驗證會非常麻煩,並且非常的不優雅。 於是, 就出現了,一種基於規則的 輸入驗證庫,通過註解即可標註驗證規則。 ...
  • 背景 因為公司一個app項目需要擴展,因為功能較多且較完整的流程與業務,而且和以前的業務關係不大,所以我整合到了 另外一個分包中(代號:newFunc,請註意是代號)進行依賴。 當我寫完這部分業務開始進行debug的時候我發現了這個錯誤。 上述中我得出already這個關鍵字,在對分包的集成測試中沒 ...
一周排行
    -Advertisement-
    Play Games
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...