Swift 實現可拖動的遮罩層,展現兩張圖片的不同處

CameronX94 7年前
   <p style="text-align:center"><img src="https://simg.open-open.com/show/4b38665b62eec228a163a4eb6aabc512.png"></p>    <p>上面這張圖來自 TinyPNG ,他們的圖片壓縮服務真的不錯,不過如果我們需要去比較這兩張圖的差異,</p>    <p>眼球就需要不停的左右移動去看兩張圖,難免會覺得看不出差異在哪裡。</p>    <p>所以如果能夠將兩張圖片堆疊在一起,中間有根桿子來讓我們滑動,通過滑動來看出兩張圖片的差異,就可以變得直觀很多。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/332516773e00448604185fac5ddd5d4a.png"></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/554ef741ee623b330b2e188948e856f2.gif"></p>    <p>這是一張在「裡冷園區」參加高空擊球活動的圖,其實從小從高空往下看都會有點恐懼,不過來到這個園區就是為了不斷突破這個恐懼感,去挑戰各種高空活動。</p>    <p>左邊看得見的部分是原圖,右邊則是修改過的圖,我們可以通過拖動中間的桿子來即時的看見兩張圖在同一個位置上的差異性。</p>    <h2>Swift實現方法</h2>    <p style="text-align:center"><img src="https://simg.open-open.com/show/e3614f9c1ed861f71c743a226f675db3.png"></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/9e9eff292f5bd8983983ab94072a49f0.png"></p>    <p>最底層,我們放了一張「原圖」,而在原圖的上面蓋著一張「修改過的圖」,而「修改過的圖」的上面我們放了一張maskView。</p>    <p>一開始我麼會將maskView設定在右側並且寬度為屏幕的一半。</p>    <h3>設定mask</h3>    <p>這裡的imageView2是指「修改過的圖」,即第二層的那張圖。</p>    <p>我們將imageView2的mask設定為maskView,也就是說, 只有maskView重疊到imageView2的部分,imageView2才會顯示出來 。</p>    <pre>  <code class="language-objectivec">imageView2.mask = maskView  </code></pre>    <h3>UIPanGesture</h3>    <p>然後給中間橘色的barImageView設置一個拖動手勢的偵測(UIPanGesture)</p>    <pre>  <code class="language-objectivec">    func setupGesture() {          barImageView.isUserInteractionEnabled = true                    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(barDidSwipe(gesture:)))          barImageView.addGestureRecognizer(panGesture)      }  </code></pre>    <p>barImageView的寬度是25,所以中心點的x可以簡單算成12.5,當使用者拖動中間的bar時,我們改變barImageView以及遮罩層的寬度即可(讓他左側跟著barImageview)。</p>    <h3>移動barImageView和maskView</h3>    <p>我們可以得到使用目前拖動的位置(point),通過檢測point.x的位置,接下來就是簡單的計算了。</p>    <pre>  <code class="language-objectivec">    func barDidSwipe(gesture:UIGestureRecognizer) {          if let panGesture = gesture as? UIPanGestureRecognizer {              let point = panGesture.location(in: view)                                          let halfBarWidth = CGFloat(12.5)              barImageView.frame.origin.x = point.x - halfBarWidth                            let newMaskViewFrame = CGRect(x: point.x,                                            y: maskView.frame.origin.y,                                            width: view.frame.width - point.x,                                            height: maskView.frame.height)              maskView.frame = newMaskViewFrame                        }                }  </code></pre>    <p> </p>    <p> </p>    <p>来自:https://ios.devdon.com/archives/483</p>    <p> </p>