<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by 陳芷慧 on Medium]]></title>
        <description><![CDATA[Stories by 陳芷慧 on Medium]]></description>
        <link>https://medium.com/@judy840103?source=rss-bf20f4bb205e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Nccc0FS6zOk2F6yL.jpg</url>
            <title>Stories by 陳芷慧 on Medium</title>
            <link>https://medium.com/@judy840103?source=rss-bf20f4bb205e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 17:09:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@judy840103/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[利用 viewDidLoad 客製 App 畫面]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8-viewdidload-%E5%AE%A2%E8%A3%BD-app-%E7%95%AB%E9%9D%A2-3d36150b6cc6?source=rss-bf20f4bb205e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d36150b6cc6</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[caemittercell]]></category>
            <category><![CDATA[viewwillappear]]></category>
            <category><![CDATA[viewdidload]]></category>
            <category><![CDATA[caemitterlayer]]></category>
            <dc:creator><![CDATA[陳芷慧]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 10:19:26 GMT</pubDate>
            <atom:updated>2024-01-30T10:19:26.201Z</atom:updated>
            <content:encoded><![CDATA[<h4>讓初始畫面出現想要的顏色、圖案和動畫</h4><h4><strong>viewDidLoad的功能特色：</strong></h4><p>・viewDidLoad()由系統自己呼叫<br>・可以在viewDidLoad下設置view的屬性，例如初始背景顏色、邊框等<br>・viewDidLoad() 只會在viewContrller首次加載的時候執行(被呼叫一次)， 如果是每次進入viewContrller時都執行的操作，就要使用viewWillAppear()</p><h4>viewDidLoad &amp; viewWillAppear比較</h4><p><strong>・viewDidLoad：初始化＆設置頁面的初始狀態<br></strong>以社群App的朋友列表頁面為例，可以在viewDidLoad()中設置初始view的樣式、初始資料，如從伺服器或本地獲取資料、cell外觀等。讓頁面載入完成後系統自動幫忙呼叫這些初始值。<br><strong>・viewWillAppear ：每次進入頁面時都執行的操作<br></strong>如果進入朋友列表頁面前可能有新的資料更新 （像新增朋友、列表狀態和排序更新），或是希望在每次顯示頁面時執行動畫特效時，就可以在viewWillAppear()中執行刷新資料的操作</p><h4>實際以viewDidLoad設定初始畫面</h4><p>開啟app後，讓系統自動讀入背景顏色、</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9TUg6holrnY9-wfry_LKqw.png" /></figure><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        //背景顏色<br>        view.backgroundColor = UIColor(red: 244/255, green: 208/255, blue: 110/205, alpha: 1)<br>        <br>        //橫幅<br>        let bannerView = SharpView(frame: CGRect(x: 0, y: 20, width: 415, height: 150))<br>        bannerView.backgroundColor = UIColor(white: 1, alpha: 0.3)<br>        view.addSubview(bannerView)<br><br>        func startRaining(){<br>        //背景下香蕉雨<br>        let bananaEmitterCell = CAEmitterCell()<br>        bananaEmitterCell.contents = UIImage(named: &quot;banana.png&quot;)?.cgImage<br>        bananaEmitterCell.birthRate = 2<br>        bananaEmitterCell.lifetime = 20<br>        bananaEmitterCell.velocity = 100<br>        bananaEmitterCell.scale = 0.1<br>        bananaEmitterCell.scaleRange = 0.3<br>        bananaEmitterCell.scaleSpeed = -0.05<br>        bananaEmitterCell.yAcceleration = 30<br>        <br>        <br>        let bananaEmitterLayer = CAEmitterLayer()<br>        bananaEmitterLayer.emitterCells = [bananaEmitterCell]<br>        bananaEmitterLayer.emitterPosition = CGPoint(x: view.bounds.width/2, y: -50)<br>        bananaEmitterLayer.emitterSize = CGSize(width: view.bounds.width, height: 0)<br>        bananaEmitterLayer.emitterShape = .line<br>        view.layer.addSublayer(bananaEmitterLayer)<br>        }<br>        <br>        <br>        // 設定香蕉gif<br>        let bananaImageView = UIImageView(frame: CGRect(x: 345, y: 54, width: 30, height: 30))<br>              view.addSubview(bananaImageView)<br>              let animatedImage = UIImage.animatedImageNamed(&quot;2e296252fda9478e872bbd809327076as66BkQL5UDSEm65N-&quot;, duration: 10)<br>               bananaImageView.image = animatedIma<br>}</pre><h4>製作香蕉雨動畫</h4><p>建立一個function來實現下香蕉雨的動畫，function中使用CAEmitterCell和 CAEmitterLayer。CAEmitterCell可以定義單一香蕉的粒子(particles)效果，CAEmitterLayer來管理粒子的發射。</p><p><a href="https://developer.apple.com/documentation/quartzcore/caemitterlayer/emitter_shape">Emitter Shape | Apple Developer Documentation</a></p><p><strong>1. CAEmitterCell : 定義單一香蕉的粒子效果</strong></p><ul><li>contents: 設定粒子的顯示內容為 &quot;banana.png&quot; 圖片。</li><li>birthRate: 每秒產生的粒子數量為 2。</li><li>lifetime: 每個粒子的生命週期為 20 秒。</li><li>velocity: 設定粒子的初始速度為 100。</li><li>scale: 設定粒子的初始縮放為 0.1。</li><li>scaleRange: 設定縮放的範圍為 0.3，使得每個粒子的縮放在初始值上再隨機增減 0.3。</li><li>scaleSpeed: 設定縮放的變化速度為 -0.05。</li><li>yAcceleration: 設定在 Y 軸方向上的加速度為 30。</li></ul><p><strong>2. CAEmitterLayer: 管理粒子的發射</strong></p><ul><li>emitterCells: 將先前定義的 bananaEmitterCell 設定為發射器的粒子。</li><li>emitterPosition: 設定粒子系統的發射位置為畫面的正中央頂部。</li><li>emitterSize: 設定粒子系統的發射大小為整個畫面的寬度，高度為 0。</li><li>emitterShape: 設定粒子系統的形狀為線性，使得粒子從一條線上發射</li></ul><p><strong>3. 最後將 </strong><strong>bananaEmitterLayer 加入到畫面的 layer 中，使效顯示在畫面上。</strong></p><ul><li>view.layer.addSublayer(bananaEmitterLayer):</li></ul><pre>func startRaining(){<br>        //背景下香蕉雨<br>        let bananaEmitterCell = CAEmitterCell()<br>        bananaEmitterCell.contents = UIImage(named: &quot;banana.png&quot;)?.cgImage<br>        bananaEmitterCell.birthRate = 2<br>        bananaEmitterCell.lifetime = 20<br>        bananaEmitterCell.velocity = 100<br>        bananaEmitterCell.scale = 0.1<br>        bananaEmitterCell.scaleRange = 0.3<br>        bananaEmitterCell.scaleSpeed = -0.05<br>        bananaEmitterCell.yAcceleration = 30<br>        <br>        <br>        let bananaEmitterLayer = CAEmitterLayer()<br>        bananaEmitterLayer.emitterCells = [bananaEmitterCell]<br>        bananaEmitterLayer.emitterPosition = CGPoint(x: view.bounds.width/2, y: -50)<br>        bananaEmitterLayer.emitterSize = CGSize(width: view.bounds.width, height: 0)<br>        bananaEmitterLayer.emitterShape = .line<br>        view.layer.addSublayer(bananaEmitterLayer)<br>        }</pre><h4>製作香蕉GIF</h4><p>可參考之前寫的這篇文章</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E5%88%A9%E7%94%A8-uiimageview-%E5%AF%A6%E7%8F%BE%E5%A4%9A%E5%BC%B5%E5%9C%96%E7%89%87%E9%80%A3%E7%BA%8C%E6%92%AD%E6%94%BE%E7%9A%84%E5%8B%95%E7%95%AB-e71dc01639d0">利用 UIImageView 實現多張圖片連續播放的動畫</a></p><h4>成品</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*aggmnlI3EGBurt0s.gif" /></figure><h4>參考文章</h4><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-caemitterlayer-%E8%A3%BD%E4%BD%9C-xmas-%E7%9A%84%E4%B8%8B%E9%9B%AA%E5%8B%95%E7%95%AB-ee5f7cae621e">利用 CAEmitterLayer 製作 Xmas 的下雪動畫</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d36150b6cc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8-viewdidload-%E5%AE%A2%E8%A3%BD-app-%E7%95%AB%E9%9D%A2-3d36150b6cc6">利用 viewDidLoad 客製 App 畫面</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[利用 UIImageView 實現多張圖片連續播放的動畫]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8-uiimageview-%E5%AF%A6%E7%8F%BE%E5%A4%9A%E5%BC%B5%E5%9C%96%E7%89%87%E9%80%A3%E7%BA%8C%E6%92%AD%E6%94%BE%E7%9A%84%E5%8B%95%E7%95%AB-e71dc01639d0?source=rss-bf20f4bb205e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e71dc01639d0</guid>
            <category><![CDATA[gif]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uiimageview]]></category>
            <dc:creator><![CDATA[陳芷慧]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 09:19:53 GMT</pubDate>
            <atom:updated>2024-01-19T09:19:53.354Z</atom:updated>
            <content:encoded><![CDATA[<h4>如何在app中放gif動圖</h4><h4>下載一張喜歡的gif</h4><p>小小兵喜歡吃banana，所以挑了張banana的gif</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/36/1*PCF51ck13JkhADiJZx4Z_g.gif" /></figure><p><a href="https://www.animatedimages.org/">Thousands of animated gifs, images, pictures &amp; animations: 100% FREE!</a></p><h4>把 gif轉成一張張png圖檔</h4><p>轉成png後，可以知道banana的gif動態是由8張圖構成。<br>把8張圖拉進Xcode專案的Assets.xcassets中</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*ySPC7IbZzLDmqQr5pPWdaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_32Yn9xthVA7lQmAHpvdrw.png" /></figure><p><a href="https://convertio.co/zh/gif-png/">GIF轉PNG轉換器。在线自由 - Convertio</a></p><h4>開始寫程式</h4><p>生成一個用來<strong>顯示香蕉動圖的</strong><strong>UIImageView</strong>後，貼在View上。<br>再生成一個<strong>裝香蕉動圖的的</strong><strong>UIImage，</strong>他有一個method叫animatedImageNamed(_:duration:)可以生成和回傳一個動態圖片。<br>參數傳入圖片名稱，和動畫持續時間 (以秒為單位)。圖片名稱只要輸入前面的部分，animatedImageNamed會自動幫忙補上後面的數字</p><pre>class func animatedImageNamed(_ name: String, duration: TimeInterval) -&gt; UIImage?</pre><p>最後讓UIImageView的image等於UIImage，也就是讓bananaImageView顯示香蕉動圖</p><pre>//生成ImageView<br>let bananaImageView = UIImageView(frame: CGRect(x: 345, y: 54, width: 30, height: 30))<br><br>//把香蕉ImageView貼在View上<br>view.addSubview(bananaImageView)<br><br>//生成裝香蕉動圖的物件，設定跑10秒<br>let animatedImage = UIImage.animatedImageNamed(&quot;2e296252fda9478e872bbd809327076as66BkQL5UDSEm65N-&quot;, duration: 10)<br><br>//把生成的香蕉動圖設定為 bananaImageView 的圖片。這樣bananaImageView 就會顯示這個動畫<br>bananaImageView.image = animatedImage</pre><h4>成品</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/0*uCbqU0e0reeCNOen.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e71dc01639d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8-uiimageview-%E5%AF%A6%E7%8F%BE%E5%A4%9A%E5%BC%B5%E5%9C%96%E7%89%87%E9%80%A3%E7%BA%8C%E6%92%AD%E6%94%BE%E7%9A%84%E5%8B%95%E7%95%AB-e71dc01639d0">利用 UIImageView 實現多張圖片連續播放的動畫</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[用AV Player 播放音效]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E7%94%A8av-player-%E6%92%AD%E6%94%BE%E9%9F%B3%E6%95%88-4bed6127b337?source=rss-bf20f4bb205e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bed6127b337</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[avplayer]]></category>
            <category><![CDATA[avfoundation]]></category>
            <dc:creator><![CDATA[陳芷慧]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 07:43:08 GMT</pubDate>
            <atom:updated>2024-01-18T10:30:43.768Z</atom:updated>
            <content:encoded><![CDATA[<h4>如何點擊後播放音效</h4><p><a href="https://developer.apple.com/documentation/avfoundation/avplayer">AVPlayer | Apple Developer Documentation</a></p><h4>功能設計目標</h4><p>使用者作答英文題目時：<br>Action: 點擊對應的中文解答按鈕<br>Event 1: 若點擊正確，就播放回答正確的音效<br>Event 2: 若點擊錯誤，就播放回答錯誤的音效</p><h4>下載正解和錯誤的音效</h4><p>上網從音效庫下載正解和錯誤音效。因為預想使用者在操作時會重複點擊按鈕，所以讓音效長度在1秒內，這樣AV Player重播才不會花太久時間。將音效拖曳到project navigator 的app資料夾下，並設定音效Destination和target</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*8A90eotQQfOo1Wqavz48MQ.png" /><figcaption>將correctSE.mp3 和 wrongSE.mp3拖曳到project navigator 下</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*bjOzYDG-X5CKBHAKbS4tmQ.png" /><figcaption>勾選音效Destination 和 Add to targets</figcaption></figure><h4>生成可以播放單次音效的AV Player</h4><ol><li>創建「正解播放器correctPlayer」和「錯誤播放器wrongPlayer</li><li>在ViewController下定義一個「點擊播放器clickPlayer」。視回答結果，將「正解播放器」或「錯誤播放器」assign給「點擊播放器」</li><li>載入音效檔案，從「App資料夾.Bundle.main」找到音效的路徑 .url<br>forResource：音檔名<br>withExtension: 音檔的副檔名</li></ol><pre>import AVFoundation<br><br>//創建兩個 AVPlayer, correctPlayer 和 wrongPlayer，它們分別用於播放正確和錯誤的音效<br>let correctPlayer = AVPlayer()<br>let wrongPlayer = AVPlayer()<br><br>//載入正解音效檔案 &quot;correctSE.mp3&quot;，並創建對應的AVPlayerItem來播放正確的音效<br>let correctSEurl = Bundle.main.url(/service/forresource: &quot;correctSE&quot;, withExtension:&quot;mp3&quot;)!<br>let correctPlayerItem = AVPlayerItem(url: correctSEurl)<br><br>//載入錯誤的音效檔案 &quot;wrongSE.mp3&quot;，並創建對應的 AVPlayerItem來播放錯誤的音效<br>let wrongSEurl = Bundle.main.url(/service/forresource: &quot;wrongSE&quot;, withExtension:&quot;mp3&quot;)!<br>let wrongPlayerItem = AVPlayerItem(url: wrongSEurl)<br><br>/*在ViewController中。同時定義一個叫做clickPlayer的AVPlayer，<br>用於處理點擊事件(回答正確/錯誤)的音效。*/<br>class ViewController: UIViewController {<br>  var clickPlayer = AVPlayer()<br>}</pre><h4>使用者點選按鈕後，觸發AVPlayer的播放指令：點擊正解響起正解音效、錯誤響起錯誤音效</h4><p>事先建好答案列表，將正解assign給案列表的第一個元素。檢查使用者點擊的按鈕選項是否等於 resultArray 中第一個元素的 rightAnswer，是的話則視為回答正確</p><p>若回答正確，則把「點擊播放器clickPlayer」設置成「正解播放器correctPlayer」再替換correctPlayer的音效為「正解音效檔案correctPlayerItem」，然後播放 clickPlayer.play()</p><p>另外因爲AV Player只能單次播放，所以播放完後要用.zero將播放進度條移回開始位置</p><p>若若選擇了錯誤答案，因clickPlayer 為變數，將對應的值設為「錯誤播放器wrongPlayer 」並同樣替換成錯誤音效後播放即可。</p><pre>@IBAction func answerClicked(_ sender: UIButton) {<br><br>        if sender.currentTitle == resultArray[0].rightAnswer {<br>            clickPlayer = correctPlayer<br>            correctPlayer.replaceCurrentItem(with: correctPlayerItem)<br>            clickPlayer.play()<br>            self.clickPlayer.seek(to: .zero)<br>           <br>        }else if sender.currentTitle != resultArray[0].rightAnswer {<br><br>            clickPlayer = wrongPlayer<br>            wrongPlayer.replaceCurrentItem(with: wrongPlayerItem)<br>            clickPlayer.play()<br>            self.clickPlayer.seek(to: .zero)<br>            }<br>        }</pre><h3>成品</h3><p><a href="https://youtube.com/shorts/KRP-8SpeAiI?feature=share">用AV Player 播放音效</a></p><h4><strong>參考文章</strong></h4><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-viewdidload-%E9%BB%9E%E4%B8%80%E9%A6%96%E6%AD%8C-%E6%92%AD%E6%94%BE%E4%B8%80%E6%AC%A1pl-bfe59e9e22c">利用 AVPlayer 播放音樂音效</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/18-%E7%A9%8D%E5%8A%9F%E5%BE%B7app-%E2%91%A3-background-music-audio-effect-%E8%AE%93app%E6%9B%B4%E7%94%9F%E5%8B%95-c6fdb80389a8">#18 積功德App－ ④ background music &amp; audio effect 讓App更生動</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-avplayerlooper-%E9%87%8D%E8%A6%86%E6%92%AD%E6%94%BE%E9%9F%B3%E6%A8%82%E5%92%8C%E5%BD%B1%E7%89%87-a9142d48465e">利用 AVPlayerLooper 重覆播放音樂和影片</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bed6127b337" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E7%94%A8av-player-%E6%92%AD%E6%94%BE%E9%9F%B3%E6%95%88-4bed6127b337">用AV Player 播放音效</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[訂飲料App]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E8%A8%82%E9%A3%B2%E6%96%99app-b756b2fef45c?source=rss-bf20f4bb205e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b756b2fef45c</guid>
            <category><![CDATA[訂飲料app]]></category>
            <category><![CDATA[textfield]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[slider]]></category>
            <dc:creator><![CDATA[陳芷慧]]></dc:creator>
            <pubDate>Tue, 15 Feb 2022 11:58:08 GMT</pubDate>
            <atom:updated>2022-02-15T11:58:08.698Z</atom:updated>
            <content:encoded><![CDATA[<h4>幫助揪團訂飲料的總召統計份量甜度冰塊</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*RwbDx1EdXQAYlfYowItTVg.png" /></figure><p>這次做一個可以方便統計飲料清單的app，方便不想手寫或打字記錄飲料清單的公司點飲料總召。總召可以傳手機給同事們，或本人直接代替幫忙點選飲料的內容，而在點選過程中選取內容就會自動列在畫面中間 (待確認訂單)，總召也可以隨時手動修改內容。在確認無誤後按確認訂單鈕，訂單就會以條列式列在下方變成不可修改的狀態 (已確認訂單)。</p><h3>功能設計</h3><h4>UISegmentedControl</h4><ul><li>選擇飲料的分量，甜度、冰塊</li><li>點選<strong>加糖</strong>和<strong>冰</strong>的區塊時，顯示可以調整甜度、冰塊細節的Slider</li></ul><h4>UISlider / UIButton</h4><ul><li>Slider的數值增減以UIButton控制 (Slider的Thumb 維持不作用)，<br>甜度的數值分為無糖(0)、微糖(0.25)、半糖(0.5)、少糖(0.75)、全糖(1); 冰塊的數值分為完全去冰(0)、去冰(0.2)、微冰(0.5)、少冰(0.8)、正常冰(1)</li></ul><h4>UITextField / UIButton</h4><ul><li>在兩個任一TextField裡輸入文字後，點選確認訂單讓文字自動跑進UILabel中以顯示逐筆訂單，UILabel中訂單無法手動更改</li><li>點選全部清空按鈕以清空Label和TextField內的文字</li></ul><h4>SegmentedControl被點選時，同步顯示文字於textField中</h4><p>當點選份量、甜度、冰塊時，對應的內容可以同時記錄在下方欄位，方便隨時做確認。</p><pre>var size = [&quot;小杯・&quot;,&quot;中杯・&quot;,&quot;大杯・&quot;]<br>var sizeIndex: Int?</pre><pre>var sugar = [&quot;無糖&quot;,&quot;加糖&quot;]<br>var sugarIndex: Int?</pre><pre>var sugarDetails = [&quot;&quot;,&quot;(微糖)&quot;,&quot;(半糖)&quot;,&quot;(少糖)&quot;,&quot;(全糖)&quot;]<br>var sDIndex: Int?<br>    <br>var ice = [&quot;・冰&quot;,&quot;・溫&quot;,&quot;・熱&quot;]<br>var iceIndex: Int?<br>    <br>var iceDetails = [&quot;(完全去冰)&quot;,&quot;(去冰)&quot;,&quot;(微冰)&quot;,&quot;(少冰)&quot;,&quot;(正常冰)&quot;]<br>var iDIndex: Int?</pre><pre>func setIndex(){<br>        var content = &quot;&quot; <br>        <br>        //如果點選了份量segmentedControl<br>        if sizeIndex != nil{<br>            content = content + size[sizeIndex!]<br>            print(&quot;sizeIndex&quot;,content)<br>        }</pre><pre>        //如果點選了甜度segmentedControl<br>        if sugarIndex != nil{<br>            content += sugar[sugarIndex!]<br>        }</pre><pre>        //如果點選了甜度細節的button<br>        if sDIndex != nil{<br>            if sugarSegmentedControl.selectedSegmentIndex != 0{<br>            content = content + sugarDetails[sDIndex!]<br>            }<br>        }</pre><pre>        //如果點選了冰塊的segmentedControl<br>        if iceIndex != nil{<br>            content = content + ice[iceIndex!]<br>        }</pre><pre>        //如果點選了冰塊細節的button<br>        if iDIndex != nil{<br>            if iceSegmentedControl.selectedSegmentIndex == 0{<br>            content = content + iceDetails[iDIndex!]<br>            }<br>        }<br>        selectedItemTextField.text = content<br>    }</pre><p>【程式說明】<br>先設定變數儲存飲料的<strong>份量(size)</strong>、<strong>甜度有無(sugar)</strong>＆<strong>甜度細節(sugarDetails)</strong>、<strong>冰溫熱(ice)</strong>＆<strong>冰塊細節(iceDetails)</strong>的array; 變數<strong>Index</strong>用來之後儲存使用者點選到的內容。</p><p>→ 因為<strong>份量</strong>、<strong>甜度有無</strong>、<strong>冰溫熱</strong>可以是未點選狀態 (nil)，所以將<strong>Index</strong>宣告成Optional。另外sugarDetails[0]本來設定為”無糖”，但為了不跟甜度SegmentedControl的無糖重複，所以為了配合同樣是五個elements的iceDetails，就維持空字串了。</p><p>接著自訂一個func將使用者選擇的甜度冰塊，儲存待確認訂單在contents (空字串)裡，並同步以文字顯現在selectedItemTextField中。</p><p>→ 將<strong>份量</strong>、<strong>甜度有無</strong>＆<strong>甜度細節</strong>、<strong>冰溫熱</strong>＆<strong>冰塊細節</strong>的屬性全部包在func中是因爲之後不論觸發任一元件，程式都要重複將前面點選過的屬性文字再顯示在textField中一次。舉例來說app啟動後，使用者與元件互動時與程式是這樣跑的：</p><p>1. 總召先選擇中杯 → <br>中的segment被點選，textField同時顯示“中杯”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*m-LfJQO6zJSy5huG0iqWiA.png" /></figure><p>2. 總召再選加糖 →<br><strong>加糖</strong>的segment<strong>被點選，</strong>textField<strong>顯示</strong>“中杯・加糖(微糖)”，並且下方會同時跑出甜度細節的slider、button、Label (因為呼叫了sugarLabelchange())<br>因slider已預設好了“微糖”的初始值，所以textField中再顯示了一次“中杯・加糖(微糖)”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ViK4ipjRTkZ70TVomiSnNQ.png" /><figcaption>textField中的文字就是右邊程式粉框上疊紅框出來的結果。</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFoR-Curoc02ZL8nrAaY4A.png" /><figcaption>繼續選擇冰塊，textField裡的文字就是深藍框到淺藍框一路覆蓋出來的結果。</figcaption></figure><p>4. 總召最後發現第一個份量選錯，應該選大杯的→</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnAtTQj9nQcurrm2cU4qbQ.png" /></figure><h4>textField中修改內容後收鍵盤</h4><p>當點選份量、甜度、冰塊時，想要手動修改內容時就可以在TextField裡叫出鍵盤，但修改完畢要收鍵盤時要如何設定呢？</p><pre>// 點空白處收鍵盤<br>    override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>      self.view.endEditing(true)<br>    }<br>    <br>// 點return鍵收鍵盤<br>    func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool {<br>        textField.resignFirstResponder();<br>       return true<br>    }</pre><p>其他詳細說明可以參考下面的文章</p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E7%94%A8-siri-%E4%BE%86%E6%AD%90%E5%8C%97%E4%BE%9B%E5%A8%81-%E4%BB%BB%E5%90%9B%E8%AA%BF%E6%95%B4%E5%AE%A2%E8%A3%BD%E7%9A%84%E5%91%8A%E7%99%BD%E8%AA%AA%E8%A9%B1-app-de31fac4a10d">用 Siri 來歐北供威─任君調整客製的告白說話 APP</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/swift-ios-app-%E4%BD%9C%E6%A5%AD-8-%E4%B8%83%E5%A4%95%E9%99%90%E5%AE%9A%E5%91%8A%E7%99%BDapp-%E7%94%A8slider%E8%AA%BF%E6%95%B4%E8%AC%9B%E8%A9%B1%E7%9A%84%E9%9F%B3%E8%AA%BF%E5%92%8C%E9%80%9F%E5%BA%A6-a89b9728fb5e">Swift iOS App | 作業#8 七夕限定告白App| 用Slider調整講話的音調和速度</a></li></ul><h4>用Button調整甜度冰塊細節，細節同步以文字顯示在Label和textField中</h4><p>設計邏輯上<strong>不能</strong>出現以下三種情況：</p><ol><li>甜度segmentedControl選擇無糖後，Label和textField中顯示無糖以外的甜度。例如Label未自動顯示無糖、textfield出現無糖(微糖)、無糖（半糖）、無糖（全糖）</li></ol><p>為了解決第一點，在slider的value為0的條件下將if sDIndex != nil 的區塊拿掉就OK了。意思是指飲料是無糖時，textField中的”無糖”文字顯示來源只會是甜度SegmentedControl。</p><pre>//當甜度slider數值為0(代表無糖)，Label也要顯示無糖 ; 甜度segmentedControl的sugarIndex數值須為0(代表無糖)，sugar[0]存入content後顯示在textField裡</pre><pre>func sugarLabelchange(){<br>        if sugarSlider.value == 0{<br>            <strong>setSugarSliderDetails(text: &quot; 無糖 &quot;, minTrackTintColor: sugarFifthColor, thumbTintColor: sugarFifthColor)</strong><br>            var content = &quot;&quot;<br>            if sizeIndex != nil{<br>                content = content + size[sizeIndex!]<br>                print(&quot;sugarS0-size&quot;,content)<br>            }<br>            <strong>sugarIndex = 0<br>            if sugarIndex != nil{<br>                content += sugar[sugarIndex!]<br>                print(&quot;sugarS0-sugar&quot;,content)<br>            }</strong><br>            if iceIndex != nil{<br>                content = content + ice[iceIndex!]<br>                print(&quot;sugarS0-ice&quot;,content)<br>            }<br>            if iDIndex != nil{<br>                if iceSegmentedControl.selectedSegmentIndex == 0{<br>                content = content + iceDetails[iDIndex!]<br>                print(&quot;sugarS0-iceD&quot;,content)<br>                }<br>            }<br>            <strong>selectedItemTextField.text = content</strong></pre><pre>}<br>    }</pre><p>2. 甜度segmentedControl選擇加糖後，Label和textField還是顯示無糖，<br>沒有自動顯示加糖、textfield出現加糖(無糖)</p><p>為了解決第二點，則在點選加糖segment後，強制將slider的value變成微糖(0.25)作為預設值，Label顯示微糖，Textfield顯示“加糖(微糖)”。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/0*0OSKvzrtOdO4b2hR.gif" /><figcaption>第一、二點解決後正確顯示的樣子</figcaption></figure><p>3. 冰塊segmentedControl選擇溫或熱後，還能用slider選擇冰塊細節，並且textField出現(完全去冰)、(去冰)、(微冰)、(少冰)、(正常)</p><p>而解決第三點的辦法就是在溫、熱被點選時仍隱藏冰塊slider，並且拿掉if iDIndex != nil 的區塊，讓冰塊細節不會出現在textField中</p><pre><a href="http://twitter.com/IBAction">@IBAction</a> func iceSegmentSelected(_ sender: UISegmentedControl) {<br>        if sender.selectedSegmentIndex == 0{<br>            iceHidden(change: false)<br>            iceValue = 0.5<br>            iceSlider.value = Float(iceValue)<br>            iceLabelChange()<br>            iceIndex = 0<br>            iDIndex = 2<br>            setIndex()<br>        <br>        //點選溫<br>        }else if sender.selectedSegmentIndex == 1{<br>            iceHidden(change: true)<br>            iceSlider.value = Float(iceValue)<br>            iceLabelChange()<br>            var content = &quot;&quot;<br>            if sizeIndex != nil{<br>                content = content + size[sizeIndex!]<br>                print(&quot;ice1-size&quot;,content)<br>            }<br>            if sugarIndex != nil{<br>                content += sugar[sugarIndex!]<br>                print(&quot;ice1-sugar&quot;,content)<br>            }<br>            if sDIndex != nil{<br>                content += sugarDetails[sDIndex!]<br>                print(&quot;ice1-sugarD&quot;,content)<br>            }<br>            iceIndex = 1<br>            if iceIndex != nil{<br>                content = content + ice[iceIndex!]<br>                print(&quot;ice1-ice&quot;,content)<br>            }<br>            selectedItemTextField.text = content</pre><pre>        //點選熱<br>        }else if sender.selectedSegmentIndex == 2{<br>            iceHidden(change: true)<br>            iceSlider.value = Float(iceValue)<br>            iceLabelChange()<br>            var content = &quot;&quot;<br>            if sizeIndex != nil{<br>                content = content + size[sizeIndex!]<br>                print(&quot;ice2-size&quot;,content)<br>            }<br>            if sugarIndex != nil{<br>                content += sugar[sugarIndex!]<br>                print(&quot;ice2-sugar&quot;,content)<br>            }<br>            if sDIndex != nil{<br>                content += sugarDetails[sDIndex!]<br>                print(&quot;ice2-sugarD&quot;,content)<br>            }<br>            iceIndex = 2<br>            if iceIndex != nil{<br>                content = content + ice[iceIndex!]<br>                print(&quot;ice2-ice&quot;,content)<br>            }<br>            selectedItemTextField.text = content<br>        }<br>    <br>     }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*05EoHhh03Xm0bv2m.gif" /><figcaption>第三點解決後正確顯示的樣子</figcaption></figure><h4>讓Label外觀為圓角，Label大小隨著文字改變</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/0*EYG2GL6ag-lQFRzh.gif" /></figure><pre>func updateSugarViewSize(){<br>        sugarLabel.sizeToFit() <br>        sugarView.layer.cornerRadius = 3<br>        sugarView.frame.size = sugarLabel.frame.size<br>    }<br>func updateIceViewSize(){<br>        iceLabel.sizeToFit()<br>        iceView.layer.cornerRadius = 3<br>        iceView.frame.size = iceLabel.frame.size<br>    }</pre><p>Label無法設定圓角但View可以，所以將View疊在Label上，圓角設定在View上; Label的大小設定sizeToFit()，讓尺寸會跟著文字內容變動。最後再將View的大小配合Label大小改變。</p><h4>按下確認訂單鈕後，待確認訂單變為已確認訂單</h4><p>當份量甜度冰塊確定不再更改時，按確定訂單按鈕就能變為已確認訂單顯示在下方欄位中。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*ejESiZM28QVDB_hhCiRSdA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*zp03fzaWyCpHfPic2yo1PQ.jpeg" /><figcaption>右圖利用AutoShrink後可以容納到17列</figcaption></figure><pre>@IBOutlet weak var memoTextField: UITextField!<br>@IBOutlet weak var selectedItemTextField: UITextField!<br>@IBOutlet weak var confirmButton: UIButton!<br>@IBOutlet weak var contentLabel: UILabel!</pre><pre>var confirmedContent = &quot;&quot;<br>var num = 1<br>    <a href="http://twitter.com/IBAction">@IBAction</a> func confirmButtonPressed(_ sender: UIButton) {<br>  <br>            contentLabel.textColor = UIColor.darkGray<br>            contentLabel.font = UIFont.systemFont(ofSize: 14)<br>            confirmedContent.append(&quot;\(num). &quot;)<br>            confirmedContent.append(selectedItemTextField.text!)<br>            confirmedContent.append(&quot;\t&quot;)<br>            confirmedContent.append(memoTextField.text!)<br>            confirmedContent.append(&quot;\n&quot;)<br>            contentLabel.text = confirmedContent<br>            selectedItemTextField.text = &quot;&quot;<br>            memoTextField.text = &quot;&quot;<br>            num = num + 1<br>        print(confirmedContent)<br>        print(&quot;sugar: \(sugarValue),ice: \(iceValue)&quot;)</pre><pre>    }</pre><p>【UILabel設定】</p><p>contentLabel的文字顏色和大小設定如下，</p><pre>contentLabel.textColor = UIColor.darkGray<br>contentLabel.font = UIFont.systemFont(ofSize: 14)</pre><p>為了讓contentLabel能夠容進多一點的文字，要將Text設定為Attributed，Lines設為 0 (代表不限制列數的最大上限)，設定AutoShrink的Minimum Font Size或Minimum Font Scale 0.5 (當文字要超出範圍時縮小字體，字體最小為14*0.5)。而設定Minimum Font Scale 0.5的結果，Label從原本只能容納8列變成可以容納17列。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*WzAQGzyTbH2eVJb7AqnPmQ.png" /></figure><p>【程式說明】</p><p>宣告一個變數confirmedContent儲存待確認訂單，和一個變數num記錄已確認的訂單編號。因為訂單編號會逐漸遞增，所以宣告在confirmButtonPressed的func外面。<br>利用append的方式將待確認訂單(selectedItemTextField)、備註欄(memoTextField)的文字和編號添加進confirmedContent中，將confirmedContent的內容設為contentLabel的文字就完成了。</p><p>為了做出已確認訂單逐筆累積在contentLabel裡，所以<br>最後還需要將待確認訂單(selectedItemTextField)和備註欄文字(memoTextField)指定為空字串讓它重新歸零、訂單編號＋1，讓下一次觸發確認訂單按鈕時，出現編號累加，後面緊接的是新的一筆訂單。</p><p>【成品】</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*EuKSVwjQLKjkYHHw.gif" /></figure><p>【專案下載】</p><p><a href="https://github.com/doobll/Order-Drinks-App">GitHub - doobll/Order-Drinks-App</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b756b2fef45c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E8%A8%82%E9%A3%B2%E6%96%99app-b756b2fef45c">訂飲料App</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[利用 page control, segmented control, button, & gesture 切換圖片內容]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8-page-control-segmented-control-button-gesture-%E5%88%87%E6%8F%9B%E5%9C%96%E7%89%87%E5%85%A7%E5%AE%B9-326e7b86967a?source=rss-bf20f4bb205e------2</link>
            <guid isPermaLink="false">https://medium.com/p/326e7b86967a</guid>
            <category><![CDATA[segmentedcontrol]]></category>
            <category><![CDATA[ibaction]]></category>
            <category><![CDATA[iboutlet]]></category>
            <category><![CDATA[page-control]]></category>
            <category><![CDATA[gestures]]></category>
            <dc:creator><![CDATA[陳芷慧]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 09:20:54 GMT</pubDate>
            <atom:updated>2022-01-15T12:22:16.949Z</atom:updated>
            <content:encoded><![CDATA[<h4>連接起StoryBoard和程式的IBOutlet &amp; IBAction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*dTfguje7zaCySr3kqu1EiA.png" /></figure><p>StoryBoard的元件設計＆程式碼就像是兩個世界互不相干，<br>要讓兩邊產生關聯達到相輔相成的作用，就要在兩者之間建立<strong>IBOutlet</strong>和<strong>IBAction。</strong></p><h3>什麼是IBOutlet ＆IBAction</h3><h4>IBOutlet</h4><p>要從程式修改Storyboard上的元件，以及在IBAction中會引用到該元件時，要透過拉IBOutlet產生變數。</p><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> volumeSlider: UISlider!</pre><h4>IBAction</h4><p>要觸發Storyboard上某元件的event，需透過拉IBAction產生function。例如：使用者點選按鈕後，才會觸發AVfoundation的說話指令。而像ImageView和Label這類純展示內容的元件則無法拉IBAction</p><pre><strong>@IBAction</strong> <strong>func</strong> adjustVolume(_ sender: UISlider)</pre><p>sender的型別可以是Any，也可以是元件本身，如果在function中會引用到元件時可以將型別改成元件本身。例如需要存取UISlider的value給說話的音量時，sender的型別就要設成UISlider後才能被存取。<br>或是前面友邦UISlider拉過IBOutlet的情況下，也可以寫成speechUtterence.volume = Float<strong>(volumeSlider.value</strong>)</p><pre>@IBAction func adjustVolume(_ sender: UISlider) {</pre><pre>speechUtterence.volume = Float<strong>(sender.value)</strong></pre><pre>}</pre><h3>如何拉 IBOutlet ＆IBAction</h3><p>選擇右上角第二個icon&gt;打開 Assistant editor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FurawE69bTQuznbnnN3nA.png" /></figure><p>IBOutlet和IBAction的程式都會寫在class的裡面。<br>Class類別中能寫的程式只有property (以變數宣告) 和 method (以function宣告)，習慣上class的上半部會放<strong>變數、</strong>下半部會放function/method<strong>。</strong></p><p>以func viewDidLoad()為分界，從StoryBoard上點選元件按著右鍵拉到func viewDidLoad() 以上會自動判定拉的是IBOutlet、以下是IBAction</p><pre>class ViewController: UIViewController {</pre><pre><strong>    <br>    @IBAction func adjustVolume(_ sender: UISlider)</strong></pre><pre><strong><br>   </strong> override func viewDidLoad() {</pre><pre>       super.viewDidLoad()<br>    // Do any additional setup after loading the view.<br>    }</pre><pre><strong>    @IBAction func adjustVolume(_ sender: UISlider){<br>    }</strong></pre><pre>}</pre><h3>製作時遇到的問題</h3><p>基本上peter提醒需特別注意的地方，我在重新練習時全部都碰上了一次orz，所以筆記在文章前面</p><ul><li>如果要幫IBOutlet和IBAction改名，直接在Assistant editor裡改名會導致程式死掉，所以可以最好刪掉重新建新的IBOutlet和IBAction，<br>或是改名後到connections inspector把原本events刪掉再重新拉一次線。</li><li>多個元件可以連同一個IBAction</li><li>如果要複製一個已經拉了IBAction的元件時，該元件的IBAction也會一起複製到新元件上 (IBOutlet不會有這個狀況)。所以要記得檢查Send Events的連線是否符合新元件的action。</li><li>拉完IBAction的Function不用特別呼叫，而是依賴使用者在app中與元件互動來執行event和action</li><li>使用者與元件互動一次＝執行一次event＝跑一次該元件連上的IBAction ＝ 執行一次該IBAction的function下的程式</li></ul><blockquote>檢查IBOutlet和IBAction的連線狀況有兩種方法：<br> 1. 從Xcode介面右側點選connections inspector<br> 2. 從Xcode介面左側元件列表對元件點選右鍵</blockquote><h3>製作介紹：用不同元件切換ImageView裡的圖片</h3><p>我要透過一組按鈕、頁面圓點、分段按鈕、手勢 (手機中可用手指滑動或電腦滑鼠觸控板操作)來切換小小兵的圖片。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*KBdsO7FbXx1y2JaE1QFXTQ.png" /></figure><h3><strong>1. 按button換圖片</strong></h3><h4><strong>StoryBoard</strong></h4><p>在StoryBoard中新增一個ImageView，同時拉圖片進Assets中。以下我拉了四隻小小兵的圖片。再新建兩個切換下一張、上一張圖片的UIButton。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*ljjY6Qyym_ijFC5EE1Mtrg.png" /></figure><h4><strong>程式碼</strong></h4><p>為button設定一個屬性叫minions，裡面存一個array包含4個小小兵的名字。再設定一個index變數，記錄現在是第幾個圖片。index = 0指的就是array裡的第一個值“Stuart”。</p><p><strong>之後每點一下按紐(=觸發一次event)就會跑一次function。</strong>直覺上function會執行index＋1切換到下一張圖，但實際上持續點按紐後，index 會從minions[0]…minions[1]..minions[2]到最後的minions[3]，但沒有第五隻小小兵(minions[4])的情況下，繼續index＋1就會爆掉。<br>所以要用(index + 1) % minions.count讓(index + 1)除以小小兵名字的數量後得到的<strong>餘數</strong>，來避免數字爆掉使程式死掉，做到圖片無限循環的效果。</p><p>切換下一張(index + 1) % minions.count</p><pre><strong>var</strong> index = 0</pre><pre>(0 + 1) % 4 的餘數 ＝ 1  //index = 1 → minions[1]<br>(1 + 1) % 4 的餘數 ＝ 2  //index = 2 → minions[2]<br>(2 + 1) % 4 的餘數 ＝ 3  //index = 3 → minions[3]<br>(3 + 1) % 4 的餘數 ＝ 0  //index = 4 → minions[0]<br>(4 + 1) % 4 的餘數 ＝ 1  //index = 1 → minions[1]</pre><p>切換上一張(index + minions.count — 1) % minions.count</p><pre><strong>var</strong> index = 0</pre><pre>(0 + 4 - 1) % 4 = 3    //index = 3 → minions[3]<br>(3 + 4 - 1) % 4 = 2    //index = 2 → minions[2]<br>(2 + 4 - 1) % 4 = 1    //index = 1 → minions[1]<br>(1 + 4 - 1) % 4 = 0    //index = 0 → minions[1]</pre><p>最後用minions[index]讀出小小兵名字(讀出來的型別是String)，<br>將他存入常數name ，<br>再將minionImageView要顯示的圖片內容UIImage傳入。</p><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> minionImageView: UIImageView!<br><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> nextButton: UIButton!<br><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> preButton: UIButton!</pre><pre><strong>let</strong> minions = [“Stuart”,”Bob”,”Jerry”,”Mel”]<br><strong>var</strong> index = 0<br></pre><pre>// 壓按鈕切換下一張<br><strong>@IBAction</strong> <strong>func</strong> nextImage(_ sender: UIButton) {</pre><pre>index = (index + 1) % minions.count<br><strong>let</strong> name = minions[index]<br>print(index,name)                    //在debugger area中驗證是否正確<br>minionImageView.image = UIImage(named: name)</pre><pre>}</pre><pre><br>// 壓按鈕切換上一張<br><strong>@IBAction</strong> <strong>func</strong> preImage(_ sender: UIButton) {</pre><pre>index = (index + minions.count - 1) % minions.count<br><strong>let</strong> name = minions[index]<br>print(index,name)                   //在debugger area中驗證是否正確<br>minionImageView.image = UIImage(named: name)</pre><pre>}</pre><h3>2. 用手勢切換圖片</h3><h4>StoryBoard</h4><p>從Library新增一個gesture，因為要用手指左右滑動換圖片，所以添加兩個<strong>Swipe Gesture Recognizer (一個當作左滑、一個右滑)</strong>，把它拖到小小兵的ImageView上。<br>ImageView平時只顯示圖片，所以要讓使用者在圖上滑動，要勾選User Interaction Enabled，允許使用者與元件互動。<br>最後回到<strong>Swipe Gesture Recognizer，</strong>在Attributes inspector選擇滑動的方向，將向左滑動當作下一頁、向右滑動是下一頁。</p><h4>程式碼</h4><p><strong>Swipe Gesture Recognizer</strong>的event和按鈕一樣都是換圖片，只差在一個手滑動一個點按鈕，所以<strong>IBAction</strong>可以連接到同一個。但要把前面按鈕的sender 型別設成Any func nextImage(_ sender:<strong> Any</strong>) 和 func preImage(_ sender: <strong>Any</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_UUVwka67i11BOjPG3Zdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c35rC0hv_nqc7bUabCZx6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISX8wp55osbQrPoRga_5rg.png" /></figure><h3>3. 用PageControl 和 SegmentedControl切換圖片</h3><h4>StoryBoard</h4><p>在Canvas上新增一個UIPageControl 和 SegmentedControl ，可以先在Attributes Inspector裡設置元件的屬性</p><h4>程式碼</h4><p>接下來要用程式實現：<br>1.<strong> 在app中點擊PageControl時</strong>，執行讓小小兵圖片切換的action，<br>並且SegmentedControl的segment必須對應到PageControl的圓點同時切換<br>2. <strong>在app中點擊SegmentedControl的segment(小小兵名字)時</strong>，執行讓小小兵圖片切換的action，<br>並且PageControl的圓點必須對應到<strong>SegmentedControl的segment</strong>同時切換</p><p>為什麼SegmentedControl的segment和PageControl的圓點要寫兩次？</p><blockquote>因為使用者點擊<strong>元件，就是觸發該元件的 event，其他沒有互動的元件就不會</strong>發生<strong>event更不會執行後續的action</strong></blockquote><p>所以在寫一個IBAction要執行的程式時，要站在那個元件的角度思考，當元件被使用者操作，例如點擊、滑動等(=event被觸發)，會希望畫面上有什麼其他的功能被執行？</p><p>恩..有觸發NPC後引發一堆任務的感覺…</p><p>回到例子上，如果點擊的是PageControl，那SegmentedControl IBAction裡的內容就不會執行，所以兩邊都要寫。同理～如果壓上下頁的按鈕時也要讓PageControl 和SegmentedControl同步動作，在button 的function下就要記得把他們的動作寫進去。<br><strong><br></strong>現在來切換圖片。<strong>PageControl有個屬性叫</strong>currentPage，第一頁的值是0、第二頁的值是1….以此類推，把它存給變數index，來控制圖片切換。<strong>SegmentedControl</strong>則是用屬性selectedSegmentIndex，默認是未選取的狀態，數值是 -1。第一段的值是0、第二段的值是1….以此類推，同樣把它存給變數index，來控制圖片切換。</p><p>最後用minions[index]讀出小小兵名字(讀出來的型別是String)，將他存入常數name ，再將minionImageView要顯示的圖片內容UIImage傳入。</p><pre>@IBOutlet weak var minionPageControl: UIPageControl!<br>@IBOutlet weak var nameSegmentedControl: UISegmentedControl!    </pre><pre>let minions = [&quot;Stuart&quot;,&quot;Bob&quot;,&quot;Jerry&quot;,&quot;Mel&quot;]<br>var index = 0</pre><pre>//點擊分頁控制後執行動作<br>@IBAction func pageControlTapped(_ sender: UIPageControl) {</pre><pre>  <br>  index = sender.currentPage                     <br>  let name = minions[index]<br>  minionImageView.image = UIImage(named: name)</pre><pre>  //從分頁控制切換圖片時，讓分段按鈕對應著切換<br>  <strong>nameSegmentedControl.selectedSegmentIndex = index</strong></pre><pre>}<br> <br>//點擊分段控制後執行動作<br>@IBAction func segmentedControlTapped(_ sender: UISegmentedControl) {</pre><pre>  index = sender.selectedSegmentIndex<br>  let name = minions[index]<br>  minionImageView.image = UIImage(named: name)</pre><pre>  //從分段按鈕選名字時，讓分頁控制對應著切換<br>  <strong>minionPageControl.currentPage = index</strong></pre><pre>}</pre><h3>成品</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*6q0QI2rzUP1H5mdi.gif" /></figure><h4>完整程式碼</h4><p><a href="https://github.com/doobll/outlet-action-and-gesture-AVSpeechSynthesizer/blob/main/outlet%2C%20action%20and%20gesture/ViewController.swift">outlet-action-and-gesture-AVSpeechSynthesizer/ViewController.swift at main · doobll/outlet-action-and-gesture-AVSpeechSynthesizer</a></p><h4>專案下載</h4><p><a href="https://github.com/doobll/outlet-action-and-gesture-practice">GitHub - doobll/outlet-action-and-gesture-practice</a></p><p><strong>想知道小小兵的說話器的製作說明請見下一篇文章<br>小小兵的AVFoundation之AVSpeechSynthesizer應用篇～</strong></p><p><a href="https://medium.com/@judy840103/%E9%96%8B%E4%B8%8D%E4%BA%86%E5%8F%A3%E7%9A%84%E5%91%8A%E7%99%BD%E5%B0%B1%E7%94%A8avspeechsynthesizer%E8%AA%AA%E5%87%BA%E5%8F%A3-a300ab05b544">開不了口的告白就用AVSpeechSynthesizer說出口</a></p><p><strong>參考文章</strong></p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E9%96%8B%E7%99%BC-ios-app-%E7%9A%84-gesture-%E6%89%8B%E5%8B%A2%E5%8A%9F%E8%83%BD-uikit-%E7%89%88%E6%9C%AC-f6cb95075705">開發 iOS App 的 Gesture (手勢)功能 — UIKit 版本</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%90%8C%E4%B8%80%E5%80%8B-event-%E9%80%A3%E4%BA%86%E5%85%A9%E5%80%8B-ibaction-fdda8e4fcfc8">同一個 event 連了兩個 IBAction !</a></li></ul><p>小小兵圖片來源</p><p><a href="https://despicableme.fandom.com/wiki/Category:Minions">Minions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=326e7b86967a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8-page-control-segmented-control-button-gesture-%E5%88%87%E6%8F%9B%E5%9C%96%E7%89%87%E5%85%A7%E5%AE%B9-326e7b86967a">利用 page control, segmented control, button, &amp; gesture 切換圖片內容</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[開不了口的告白就用AVSpeechSynthesizer說出口]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E9%96%8B%E4%B8%8D%E4%BA%86%E5%8F%A3%E7%9A%84%E5%91%8A%E7%99%BD%E5%B0%B1%E7%94%A8avspeechsynthesizer%E8%AA%AA%E5%87%BA%E5%8F%A3-a300ab05b544?source=rss-bf20f4bb205e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a300ab05b544</guid>
            <category><![CDATA[iboutlet]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ibaction]]></category>
            <category><![CDATA[avspeechsynthesizer]]></category>
            <category><![CDATA[avfoundation]]></category>
            <dc:creator><![CDATA[陳芷慧]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 09:18:04 GMT</pubDate>
            <atom:updated>2022-01-15T12:23:38.889Z</atom:updated>
            <content:encoded><![CDATA[<h4>連接起StoryBoard和程式的IBOutlet &amp; IBAction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*PUkf67JCFAntW1r20YCJBg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*2aTqRjWtAH-ZBCUrxP0xbQ.jpeg" /></figure><p><a href="https://medium.com/@judy840103/%E5%88%A9%E7%94%A8-page-control-segmented-control-button-gesture-%E5%88%87%E6%8F%9B%E5%9C%96%E7%89%87%E5%85%A7%E5%AE%B9-326e7b86967a">利用 page control, segmented control, button &amp; gesture 切換圖片內容</a></p><p>繼上一篇利用IBOutlet &amp; IBAction建立起元件和程式間的橋樑，做出換圖片的效果，這篇是AVFoundation之AVSpeechSynthesizer的應用篇</p><h3>本次運用到以下功能：</h3><h4><strong>小小兵說話器</strong></h4><ul><li>點選UIStepper以固定數值調整說話音高、速度</li><li>滑動UISlider調整說話音量</li><li>讓UILabel的數值隨UIStepper和UISlider的數值變動</li><li>點選UIButton念出預設的文字，並包含已設定好的屬性</li></ul><h4><strong>藍色說話器</strong></h4><ul><li>讓AVSpeechSynthesizer的說話內容為UITextView填入的文字</li><li>用if else控制UIButton說話的播放、暫停、停止</li><li>點選UIButton收鍵盤</li><li>用UISegmentedControl選擇說話語言</li><li>滑動UISlider時對應的數值顯示在UILabel上</li><li>用if else控制UISwitch開關的條件</li><li>利用亂數隨機設定單一/全部說話屬性</li><li>點選UIButton讓說話屬性回到初始設定</li><li>利用String Interpolation(字串置換)印出數值</li><li>學習呼叫拉了IBAction的funciton</li></ul><h4>元件外觀調整說明</h4><p><strong>View<br></strong>我在小小兵說話器和藍色說話器的說話屬性的元件們下面墊了一個View，想用來凸顯調整屬性功能的區塊。然後試了兩種做法來調整View的外觀：</p><p>1. 小小兵在StoryBoard新增View元件後，從程式碼自訂function來設定View的圓角、邊框寬度和顏色後，在ViewDidLoad裡呼叫setViewAttribute()，讓View的外觀在app一啟動就顯現。</p><pre>@IBOutlet weak var attributeView: UIView!</pre><pre><strong>func setViewAttribute(){<br>        attributeView.layer.borderWidth = 5<br>        attributeView.layer.borderColor = UIColor.systemGray4.cgColor<br>        attributeView.layer.cornerRadius = 10<br>        attributeView.clipsToBounds = true<br>    }</strong></pre><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Do any additional setup after loading the view.<br>       <strong> setViewAttribute()</strong></pre><pre>}</pre><p>2. 藍色說話器則是直接在StoryBoard的Identity Inspector的 User Defined Runtime Attributes 幫View設定圓角，這個作法就不用用到viewDidLoad()。圓角效果同樣要在啟動app後才看的出來。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*djZAKePsI_Fvm-CNibyb4A.png" /></figure><p><strong>Switch</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/68/1*3XOcoU0_DaDsZOAprtCuEg.png" /><figcaption>默認On顏色</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/76/1*7luPIN3jI5jf8pOKNRPtAQ.png" /><figcaption>默認Off顏色</figcaption></figure><p>在StoryBoard中調整Switch的外觀，Switch的紐和在On狀態下的底色可以透過onTint和ThumbTint設定。<br>尷尬的是Switch在默認的off狀態下貼在View上會消失。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/86/1*nXnc0eC2tEovG04gxPMHeQ.png" /><figcaption>設定後On</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/78/1*YWgr2DYsA7c2A42Gha0Zmg.png" /><figcaption>設定後Off</figcaption></figure><p>接著設定Background藍色，Switch卻變成長方形，所以我同樣在Identity Inspector的 User Defined Runtime Attributes 幫background設定和Switch默認相同大小的圓角15，解決了這個問題。</p><h4>元件初始數值設定</h4><p><strong>UISlider和UIStepper的初始數值設定</strong></p><p>在StoryBoard設定的元件數值(例如value、Maximum、Minimum、Step等)會為元件初始值，如果後續想要隨著event的觸發變更，就要寫在IBAction中。</p><p>而UISlider和UIStepper因為設定用來控制相關的聲音屬性，<br>所以是Maximum、Minimum是依照Utterance屬性的最大、最小值去設定的。</p><blockquote>volume：音量，min-max(0–1)<br>pitchMultiplier：音高，min-max(0.5–2.0)<br>rate：語速，min-max(0–1.0)</blockquote><p>關於AVFoundation的基礎應用可以參考下面文章</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E7%94%A8-swift-%E6%89%93%E9%80%A0%E8%B7%B3%E8%88%9E%E6%A9%9F%E5%99%A8%E4%BA%BA-boogiebot-8b164b41136f">用API和AVFoundation打造唱歌跳舞機器人</a></p><h3>學習使用 AVSpeechSynthesizer 講話</h3><h4>小小兵說話器AVFoundation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/0*U_RbCkh2qyGqrYzk.gif" /></figure><p>說話功能相關的四個元件執行IBAction由上至下，每個func裡都用print在debug area顯示數值:</p><ul><li>UIButton : 設定說英國腔後，執行說話speak</li><li>UIStepper : 調整音高 ＆ 音高數值同步顯示在Label上</li><li>UIStepper：調整語速＆ 語速數值同步顯示在Label上</li><li>UISlider：調整音量＆ 音量數值同步顯示在Label上</li></ul><p>因為四個元件的IBAction裡都有引用到常數sythesizer和speechUtterence，<br>所以<strong>生成合成器</strong>let<strong> </strong>sythesizer = AVSpeechSynthesizer()<strong>和說話內容</strong>let<strong> </strong>speechUtterence = AVSpeechUtterance(string: “Bello I love banana “)要寫在IBAction的外面，如果寫在四個任一元件IBAction內的話，會有讀不到的問題。</p><pre><strong><br>import</strong> UIKit<br><strong>import</strong> AVFoundation</pre><pre>class ViewController: UIViewController {</pre><pre> @IBOutlet weak var attributeView: UIView!<br> @IBOutlet weak var pitchStepper: UIStepper!<br> @IBOutlet weak var speedStepper: UIStepper!<br> @IBOutlet weak var volumeSlider: UISlider!<br> @IBOutlet weak var pitchValueLabel: UILabel!<br> @IBOutlet weak var speedValueLabel: UILabel!<br> @IBOutlet weak var volumeValueLabel: UILabel!</pre><pre><strong> let sythesizer = AVSpeechSynthesizer()<br> let speechUtterence = AVSpeechUtterance(string: &quot;Bello I love   banana &quot;)</strong></pre><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Do any additional setup after loading the view.<br>        setViewAttribute()<br>}</pre><pre><a href="http://twitter.com/IBAction">@IBAction</a> func speak(_ sender: UIButton) {<br>       <br>        speechUtterence.voice = AVSpeechSynthesisVoice(language:  &quot;en-GB&quot;)<br>        sythesizer.speak(speechUtterence)<br>        print(pitchStepper.value,speedStepper.value,volumeSlider.value)<br>        <br>    }</pre><pre><strong>//調整Slider音高數值＋Label顯示音高數值</strong></pre><pre><a href="http://twitter.com/IBAction">@IBAction</a> func adjustPitch(_ sender: UIStepper) {<br>        speechUtterence.pitchMultiplier = Float(pitchStepper.value)<br>        pitchValueLabel.text = String(format: &quot;%.2f&quot;, sender.value)<br>        print(&quot;pitchStepper&quot;,sender.value)<br>    }</pre><pre><strong>//調整Slider語速數值＋Label顯示語速數值</strong></pre><pre><a href="http://twitter.com/IBAction">@IBAction</a> func adjustSpeed(_ sender: UIStepper) {<br>        speechUtterence.rate = Float(speedStepper.value)<br>        speedValueLabel.text = String(format: &quot;%.2f&quot;, sender.value)<br>        print(&quot;rateStepper&quot;,sender.value)<br>    }</pre><pre><strong>//調整Slider音量數值＋Label顯示音量數值</strong>    </pre><pre><a href="http://twitter.com/IBAction">@IBAction</a> func adjustVolume(_ sender: UISlider) {<br>        speechUtterence.volume = Float(volumeSlider.value)<br>        volumeValueLabel.text = String(format: &quot;%.2f&quot;, sender.value)<br>        print(&quot;volumeSlider&quot;,sender.value)<br>    }</pre><pre>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FX0e_9KAIoRA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DX0e_9KAIoRA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FX0e_9KAIoRA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/efd9b37c42d1ebd95810a440d6a654b6/href">https://medium.com/media/efd9b37c42d1ebd95810a440d6a654b6/href</a></iframe><h4>藍色說話器AVFoundation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/0*ldoKyqkTp_dyJbry.gif" /></figure><p>藍色說話器是微進階版，利用了更多元件來測試功能，並且將每個說話屬性儲存為ViewController的property，避免每次執行function後數值就被清掉。最後在func尾用把數值變字串的方式\( )print出ViewController的property數值，方便從Xcode的debug area確認每個func是否有跑出正確的結果。</p><p>功能設計相較小小兵說話器，藍色說話器為了選擇障礙的夥伴們新增了兩種隨機按鈕：一種針對單一屬性隨機調整UISlider數值、另一種針對全部屬性隨機調整UISlider數值，透過隨機鈕選到想要的數值並將其相對應的UISwitch切換至ON把數值固定住，就不用擔心動到已確認的值，可以放心的隨機選取剩下的屬性數值啦！</p><p>如果不想要隨機跑數字時也可以手動調整，與小小兵說話器在UIStepper跟UISlider被觸發後才改變數值不同，藍色說話器是先自訂function，其中包含說話的屬性。<br>合成器的說話的內容是TextView中輸入的文字，還新增了三種語言選項，在念出中、英，或日文中途可以隨時按暫停和停止。設定好說話屬性後，再執行說話speak。最後再playButton的IBAction裡呼叫自訂的function。</p><pre><strong>//說話屬性存成ViewController的property</strong></pre><pre>var volumeValue = 0.5<br>var rateValue = 0.5<br>var pitchValue = 1.0<br>let synthesizer = AVSpeechSynthesizer()<br>let language = [&quot;zh-TW&quot;,&quot;en-US&quot;,&quot;ja-JP&quot;]<br>var index = 0</pre><pre><strong>//自訂合成器說話屬性func</strong></pre><pre>func speak(language:String){<br>        let speechUtterance = AVSpeechUtterance(string: textView.text!)<br>        volumeValue = Double(volumeSlider.value)<br>        rateValue = Double(rateSlider.value)<br>        pitchValue = Double(pitchSlider.value)<br>        speechUtterance.volume = volumeSlider.value<br>        speechUtterance.rate = rateSlider.value<br>        speechUtterance.pitchMultiplier = pitchSlider.value<br>        speechUtterance.voice = AVSpeechSynthesisVoice(language:language)<br>        synthesizer.speak(speechUtterance)</pre><pre>}</pre><pre><strong>//play按鈕</strong></pre><pre><a href="http://twitter.com/IBAction">@IBAction</a> func play(_ sender: UIButton) {<br>        if synthesizer.isSpeaking == false{<br>            index = languageSegmentedControl.selectedSegmentIndex<br>            let selectedVoice = language[index]<br>            speak(language: selectedVoice)<br>        }else{<br>            synthesizer.continueSpeaking()<br>        }<br>        print(&quot;languageIndex:&quot;,index)<br>        print(&quot;play volume: \(volumeValue), rate: \(rateValue),pitch: \(pitchValue)&quot;)<br>        view.endEditing(true)  <strong>//點選播放鍵後收鍵盤</strong><br>        <br>    }</pre><p>而三個UISlider的action都是被滑動時左側的Label同步顯示數值，所以可以拉到同一個<a href="http://twitter.com/IBAction">@IBAction</a> func changeLabelValue下。<br>關於Label顯示的格式，”%.2f”代表顯示小數點後兩位</p><pre><a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var volumeSlider: UISlider!<br><a href="http://twitter.com/IBOutlet">@IBOutlet</a> weak var volumeShuffleButton: UIButton!</pre><pre><strong>//滑動全部slider數值時，讓Label數值跟著變動</strong></pre><pre>    <a href="http://twitter.com/IBAction">@IBAction</a> func changeLabelValue(_ sender: Any) {<br>        volumeLabel.text = String(format: &quot;%.2f&quot;, volumeSlider.value)<br>        rateLabel.text = String(format: &quot;%.2f&quot;, rateSlider.value)<br>        pitchLabel.text = String(format: &quot;%.2f&quot;, pitchSlider.value)<br>    }</pre><pre><strong><br>//針對音量屬性隨機設定slider數值，讓音量Label數值跟著變動</strong><br>   <br>    <a href="http://twitter.com/IBAction">@IBAction</a> func volumeShuffleValue(_ sender: Any) {<br>        volumeValue = Double.random(in: 0...1)<br>        volumeSlider.value = Float(volumeValue)<br>        print(&quot;volumeRandom:\(volumeValue)&quot;)<br>        volumeLabel.text = String(format:&quot;%.2f&quot;,volumeSlider.value)</pre><pre>    }</pre><pre><strong>// 隨機設定全部屬性的slider數值，讓全部Label數值跟著變動</strong><br>    <br>    <a href="http://twitter.com/IBAction">@IBAction</a> func setAllValueRandomly(_ sender: UIButton) {<br>        <strong>if volumeSwitch.isOn == false{<br>            self.volumeShuffleValue(self)<br>        }</strong><br>        if rateSwitch.isOn == false{<br>            self.rateShuffleValue(self)<br>        }<br>        if pitchSwitch.isOn == false{<br>            self.pitchShuffleValue(self)<br>        }</pre><pre>        print(&quot;All Randomly set volume:\(volumeValue),rate:\     <br>        (rateValue),pitch:\(pitchValue)&quot;)<br>    }</pre><pre><strong>//switch初始是off,如果on了就無法操作slider和隨機鈕(固定住volumeSlider的值)</strong><br>   <br>    <a href="http://twitter.com/IBAction">@IBAction</a> func volumeIsSwitchedOn(_ sender: UISwitch) {<br>        if sender.isOn{<br>            volumeSlider.isEnabled = false<br>            volumeShuffleButton.isEnabled = false<br>        }else{<br>            volumeSlider.isEnabled = true<br>            volumeShuffleButton.isEnabled = true<br>        }<br>    }</pre><p>此外，因為在程式前面宣告了class ViewController 屬性，用來存取所有元件func執行過程中的說話屬性數值。<br><strong> </strong>var volumeValue = 0.5<br>var rateValue = 0.5<br>var pitchValue = 1.0<br>let language = [&quot;zh-TW&quot;,&quot;en-US&quot;,&quot;ja-JP&quot;] <br>var index = 0</p><p>所以在設定resetButton時，直接在他的func中將初始值再儲存給屬性就好。<br>（之後有機會用struct來定義新的型別後就不用像class要宣告一堆變數看起來落落長又很繁瑣）</p><p>除了透過點選resetButton回歸初始值以外，也要讓App一啟動就是初始狀態，所以ViewDidLoad的func裡也要呼叫resetButton的func updateAllValue()。<br>但因為是拉了IBAction的func不能按一般方式呼叫，但又不想再自訂一個一樣的function執行初始值，所以我找到了呼叫IBAction function的方式：</p><p><a href="https://stackoverflow.com/questions/26349426/swift-call-ibaction-method-in-viewdidload-without-parameter">Swift - call @IBAction method in viewDidLoad without parameter</a></p><pre> class ViewController: UIViewController {  <strong>  </strong></pre><pre><strong>    var volumeValue = 0.5<br>    var rateValue = 0.5<br>    var pitchValue = 1.0</strong><br>    <strong>let language = [&quot;zh-TW&quot;,&quot;en-US&quot;,&quot;ja-JP&quot;]<br>    var index = 0</strong></pre><pre>    let synthesizer = AVSpeechSynthesizer()</pre><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Do any additional setup after loading the view.<br>       <strong> self.updateAllValue(self)</strong><br>    }</pre><pre>//1. 將全部slider和Label數值回歸初始值<br>//2. 如果有任何switch是on的狀態，全部回關off (slider數值才能變動)<br>//3. 讓各slider的隨機鈕回歸可選取狀態<br>    <br>     <a href="http://twitter.com/IBAction">@IBAction</a> func updateAllValue(_ sender: Any) {<br><strong>        volumeValue = 0.5<br>        rateValue = 0.5<br>        pitchValue = 1.0</strong><br>        <br>        volumeSlider.value = Float(volumeValue)<br>        rateSlider.value = Float(rateValue)<br>        pitchSlider.value = Float(pitchValue)<br>        volumeLabel.text = String(format: &quot;%.2f&quot;, volumeValue)<br>        rateLabel.text = String(format:&quot;%.2f&quot;,rateValue)<br>        pitchLabel.text = String(format:&quot;%.2f&quot;,pitchValue)<br>        <br>        languageSegmentedControl.selectedSegmentIndex = index<br>        <br>        if volumeSwitch.isOn{<br>            volumeSwitch.isOn = false<br>            volumeSlider.isEnabled = true<br>            volumeShuffleButton.isEnabled = true<br>            <br>        }<br>        if rateSwitch.isOn{<br>            rateSwitch.isOn = false<br>            rateSlider.isEnabled = true<br>            rateShuffleButton.isEnabled = true<br>            <br>        }<br>            <br>        if pitchSwitch.isOn{<br>            pitchSwitch.isOn = false<br>            pitchSlider.isEnabled = true<br>            pitchShuffleButton.isEnabled = true<br>        }<br>        print(&quot;updated volume:\(volumeValue),rate:\(rateValue),pitch:\(pitchValue)&quot;)<br>            <br>    }</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoJ03DoeHcbQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoJ03DoeHcbQ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d18caca42183db4f1c2d677dad9e5269/href">https://medium.com/media/d18caca42183db4f1c2d677dad9e5269/href</a></iframe><h4>完整程式碼</h4><p><a href="https://github.com/doobll/AVSpeechSynthesizer_blue/blob/main/AVSpeechSynthesizer/ViewController.swift">AVSpeechSynthesizer_blue/ViewController.swift at main · doobll/AVSpeechSynthesizer_blue</a></p><h4>專案下載</h4><p><a href="https://github.com/doobll/AVSpeechSynthesizer_blue">GitHub - doobll/AVSpeechSynthesizer_blue</a></p><h4><strong>其他小小注意</strong></h4><ol><li><strong>匯入的函式庫</strong><strong>import AVFoundation</strong>要寫在<strong>class</strong> ViewController: UIViewController的外面<strong>。<br> → 因為是整個檔案</strong>匯入AVFoundation的函式庫</li><li><strong>說話的屬性們</strong>和<strong>用合成器念出要說的話</strong>如果寫在同一個func下(藍色說話器的程式寫法)，要注意<strong>說話的屬性們</strong>一定要寫在<strong>用合成器念出要說的話</strong>之前。<br> → 如果合成器都講完話了才去設定講話屬性就來不及了！<br>(當func越寫越多，這點會意外變成盲點要特別留意）</li></ol><p><strong>參考文章</strong></p><p>String的數值格式</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/swift-%E9%80%8F%E9%81%8E-string-%E8%AE%93%E6%95%B8%E5%80%BC%E6%A0%BC%E5%BC%8F%E5%8C%96%E5%91%88%E7%8F%BE-%E6%95%B4%E6%95%B8%E8%A3%9C%E9%9B%B6-%E5%B0%8F%E6%95%B8%E5%9B%9B%E6%8D%A8%E4%BA%94%E5%85%A5%E8%87%B3%E7%AC%AC%E5%B9%BE%E4%BD%8D%E6%95%B8-eefb15b998b6">【Swift】透過 String 讓數值格式化呈現(整數補零、小數四捨五入至第幾位數)</a></p><p>顏色挑選</p><p><a href="https://colorhunt.co/palette/1a374d4068826998abb1d0e0">Color Palette: #1A374D #406882 #6998AB #B1D0E0 - Color Hunt</a></p><p>功能及程式參考</p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/13-%E6%84%9B%E9%BA%97%E7%B5%B2%E7%9A%84%E4%BB%99%E5%A2%83-%E8%AA%BF%E8%89%B2%E5%A4%A7%E5%B8%AB-%E5%8A%A0%E4%B8%8A%E4%BA%82%E6%95%B8-43d55f076ead">#13 愛麗絲的仙境 — 調色大師 (加上亂數)</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E7%94%A8-siri-%E4%BE%86%E6%AD%90%E5%8C%97%E4%BE%9B%E5%A8%81-%E4%BB%BB%E5%90%9B%E8%AA%BF%E6%95%B4%E5%AE%A2%E8%A3%BD%E7%9A%84%E5%91%8A%E7%99%BD%E8%AA%AA%E8%A9%B1-app-de31fac4a10d">用 Siri 來歐北供威─任君調整客製的告白說話 APP</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a300ab05b544" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E9%96%8B%E4%B8%8D%E4%BA%86%E5%8F%A3%E7%9A%84%E5%91%8A%E7%99%BD%E5%B0%B1%E7%94%A8avspeechsynthesizer%E8%AA%AA%E5%87%BA%E5%8F%A3-a300ab05b544">開不了口的告白就用AVSpeechSynthesizer說出口</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[利用 UIBezierPath 設計特別形狀的圖片 — 自定義斜邊]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8-uibezierpath-%E8%A8%AD%E8%A8%88%E7%89%B9%E5%88%A5%E5%BD%A2%E7%8B%80%E7%9A%84%E5%9C%96%E7%89%87-%E8%87%AA%E5%AE%9A%E7%BE%A9%E6%96%9C%E9%82%8A-5ce4f6981341?source=rss-bf20f4bb205e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ce4f6981341</guid>
            <category><![CDATA[uibezierpath]]></category>
            <category><![CDATA[hypotenuse]]></category>
            <category><![CDATA[background]]></category>
            <category><![CDATA[shapes]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[陳芷慧]]></dc:creator>
            <pubDate>Wed, 22 Dec 2021 18:44:44 GMT</pubDate>
            <atom:updated>2021-12-26T06:40:32.561Z</atom:updated>
            <content:encoded><![CDATA[<h3>利用 UIBezierPath 設計特別形狀的圖片 — 自定義斜邊</h3><h3>自訂繼承 UIView 的類別</h3><p>除了直接用UIBezierPath畫一個有斜邊的形狀貼在view上以外，還有一個自訂繼承 UIView 的類別的方法。</p><h4>1. 建立一個UIView</h4><p>建立一個UIVIew，因為要當作標題的底圖，所以取名為bannerView<br>設定背景顏色是帶透明的白色，貼在View上，View有預先設成想要的黃色，所以不用擔心完成後看不到bannerView。<br>UIVIew的寬度設定與螢幕同寬，高度隨意。</p><pre>let bannerView = <strong>UIView</strong>(frame: CGRect(x: 0, y: 20, width: 415, height: 150))</pre><pre>bannerView.backgroundColor = UIColor(white: 1, alpha: 0.3)</pre><pre>view.addSubview(bannerView)</pre><h4>2. 在Xcode的上方menu點選file&gt;new&gt;file，選擇Cocoa Touch Class</h4><p>建立Cocoa Touch Class後，Class(類別)欄位填寫SharpView<br>Subclass欄位填寫UIView，讓SharpView可以繼承UIView 的類別</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lxGuBlrBnaiUq_WTQoYPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMGegxzZ_psgfXdBV2XSoA.png" /></figure><h4>3. 在自訂SharpView的類別下寫斜邊程式</h4><p>設定路徑時想像要在UIView上畫什麼形狀，我想要畫長方形，並且其中一邊改斜邊。<br>開始畫之前，參照UIView的寬高去設定畫線的座標會比較好抓位置。<br>bounds指的是該view在本身座標系統的位置和尺寸 (參照點是本身座標系統)，所以下面是以UIView本身的寬高數值來設定畫線座標。</p><pre>let rectPath = UIBezierPath()</pre><pre>//設計路徑<br>//從左上角(0,0)開始<br>rectPath.move(to: CGPoint.zero)</pre><pre>//從(0,0)畫線到(415,0)<br>rectPath.addLine(to: CGPoint(x: bounds.width, y: 0))</pre><pre>//從(415,0)畫線到(415,140)<br>rectPath.addLine(to: CGPoint(x: bounds.width, y: bounds.height))</pre><pre>//從(415,140)畫線到(0,140 * 0.7)<br>rectPath.addLine(to: CGPoint(x: 0, y: bounds.height * 0.85))</pre><pre>//從(0,140 * 0.7)畫直線回(0,0)<br>rectPath.close()</pre><pre>//顯示路徑<br>let rectLayer = CAShapeLayer()</pre><pre>rectLayer.path = rectPath.cgPath</pre><pre>layer.mask = rectLayer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42Mlq7LByxcnbh_u3O6kIQ.png" /></figure><h4>4. 將UIView的類別改成自訂的SharpView類別</h4><p>回到ViewController的頁面下，將bannerView的<strong>UIView</strong>類別改成<strong>SharpView</strong></p><pre>let bannerView = <strong>UIView</strong>(frame: CGRect(x: 0, y: 20, width: 415, height: 150))</pre><pre>bannerView.backgroundColor = UIColor(white: 1, alpha: 0.3)</pre><pre>view.addSubview(bannerView)</pre><h4>成品</h4><p>看看小小兵後面那個白色透明的Banner!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*MVJ3eub80DAD5v74TOFABA.png" /></figure><p>至於如何用UIBezierPath繪製，包括小小兵是怎麼繪製的可以參考下面文章喔！</p><p><a href="https://medium.com/@judy840103/%E9%81%8B%E7%94%A8-uibezierpath-cashapelayer-%E7%B9%AA%E8%A3%BD%E5%B0%8F%E5%B0%8F%E5%85%B5-b85874ae8d06">運用 UIBezierPath、CAShapeLayer 繪製小小兵</a></p><p><strong>參考文章</strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-uibezierpath-%E8%A8%AD%E8%A8%88%E7%89%B9%E5%88%A5%E5%BD%A2%E7%8B%80%E7%9A%84%E5%9C%96%E7%89%87-%E6%AF%94%E6%96%B9%E6%96%9C%E9%82%8A-%E6%84%9B%E5%BF%83-9741747f0063">利用 UIBezierPath 設計特別形狀的圖片 — 比方斜邊 &amp; 愛心</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ce4f6981341" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8-uibezierpath-%E8%A8%AD%E8%A8%88%E7%89%B9%E5%88%A5%E5%BD%A2%E7%8B%80%E7%9A%84%E5%9C%96%E7%89%87-%E8%87%AA%E5%AE%9A%E7%BE%A9%E6%96%9C%E9%82%8A-5ce4f6981341">利用 UIBezierPath 設計特別形狀的圖片 — 自定義斜邊</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[運用 UIBezierPath、CAShapeLayer 繪製小小兵]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E9%81%8B%E7%94%A8-uibezierpath-cashapelayer-%E7%B9%AA%E8%A3%BD%E5%B0%8F%E5%B0%8F%E5%85%B5-b85874ae8d06?source=rss-bf20f4bb205e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b85874ae8d06</guid>
            <category><![CDATA[cashapelayer]]></category>
            <category><![CDATA[drawwithcode]]></category>
            <category><![CDATA[uibezierpath]]></category>
            <category><![CDATA[minions]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[陳芷慧]]></dc:creator>
            <pubDate>Wed, 22 Dec 2021 18:30:32 GMT</pubDate>
            <atom:updated>2022-01-10T05:00:14.919Z</atom:updated>
            <content:encoded><![CDATA[<h4>利用UIBezierPath繪製路徑、CAShapeLayer產生形狀</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*B_aL7UcOVdOGCUA7-pteYQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*pEZfdXO7EHcmkryYqbNpSQ.jpeg" /><figcaption>黃色是原圖・ 紫色是程式繪製</figcaption></figure><h4>製作檔案</h4><p><a href="https://github.com/doobll/minion_Drawing">GitHub - doobll/minion_Drawing</a></p><h4><strong>本次繪製用到以下功能：</strong></h4><ol><li><strong>利用UIBezierPath繪製路徑</strong></li><li><strong>利用CAShapeLayer產生形狀</strong></li><li>利用 CAGradientLayer &amp; mask 讓 CAShapeLayer 繪製的形狀變漸層</li><li>使用 CABasicAnimation 設定動畫</li></ol><p>這次製作專案比較特殊且不同於以往：這次建立的是Swift UI專案。好處就是，只要程式變動都可以即時用Swift UI 的 live preview預覽效果。例如座標標錯下錯筆、顏色挑錯變災難等等，都可以馬上看到、馬上修正，不用特別按Play啟動模擬器看畫面。</p><h3>繪製特定形狀的三個步驟</h3><ol><li><strong>利用 UIBezierPath 繪製形狀的路徑 </strong>→（此時路徑畫完還不會顯示在模擬器上）<br> move(to:) → 移動到某座標<br> addLine(to:) → 加直線<br> addQuadCurve(to:controlPoint:) → 用一個控制點把直線拉成弧形<br> addCurve(to:controlPoint1:controlPoint2:) → 用兩個控制點把直線拉成 兩個弧形<br>close() → 自動連“直線”到起點座標</li><li><strong>產生 CAShapeLayer，將UIBezierPath 路徑變成形狀。</strong>→（路徑及屬性顯示在模擬器上）<br>strokeColor → 線條顏色<br>lineWidth → 線條寬度<br>fillColor → 形狀填色，型別是cgColor</li><li><strong>利用 addSublayer 把 CAShapeLayer貼在view上。<br></strong>把CAShapeLayer貼在view上，讓CAShapeLayer變成view的subLayer</li></ol><h4>最後使用 SwiftUI 預覽 UIBezierPath 的繪圖結果</h4><p>SwiftUI的live view會自動跑修改結果，也可以按option+command+p preview</p><h3>繪製過程介紹</h3><h4>小小兵的繪製規劃</h4><ul><li>將網路找的原圖用一個ImageView顯示疊在view上，將UIBezierPath直接畫在原圖上</li><li>查詢圖片座標。據說使用Illustrator有錨點可以清楚的確認座標，比較好畫曲線 <a href="https://yangcha.github.io/iview/iview.html">https://yangcha.github.io/iview/iview.html</a></li><li>分解小小兵的部位：<br>1. 頭髮四根分開畫<br>2. 身體、手臂、手、鞋子、褲子、鏡片、瞳孔只畫左半邊，<br>右半邊以CGAffineTransform做位移和翻轉。如果鞋子會蓋住身體的情況，還是要盡量把身體畫完整。<br>3. 畫褲子Logo</li><li>寫小小兵的名字Kevin，做出漸層效果</li></ul><h4><strong>UIBezierPath 畫路徑</strong></h4><p>一開始繪製的時遇到了一個盲點，認為都要<strong>move(to:)</strong>該線的起點後才能<strong>addLine(to:) </strong>線的終點。如畫四根頭髮時，都要從髮尾回到同一個起點才能畫下一根。</p><p>但上述作法到繪製身體時就行不通了，例如從頭頂到身體是一個曲線＋直線＋曲線的連續線條，因為<strong>addLine()</strong>或<strong>addQuadCurve(to:controlPoint:)</strong>會將上一條線的終點座標作為起點下筆，所以不用每次都使用<strong>move(to:)</strong>。<br>我們可以把move(to:)想像成是<strong>提筆到要下筆的位置</strong>，而畫連續線條時過程不需要提筆對吧？</p><p>畫頭毛，每條頭髮的起點都是<strong>(x: 140, y: 125)，所以每根頭毛都要從髮尾用move(to:)移動回來髮根(x: 140, y: 125)</strong></p><pre><strong>let</strong> hairPath = UIBezierPath()</pre><pre>//畫第一根頭髮<br><strong>hairPath.move(to: CGPoint(x: 140, y: 125))</strong><br>hairPath.addQuadCurve(to: CGPoint(x: 112, y: 76), controlPoint: CGPoint(x: 133, y: 93))</pre><pre>//畫第二根頭髮<br><strong>hairPath.move(to: CGPoint(x: 140, y: 125))</strong><br>hairPath.addQuadCurve(to: CGPoint(x: 122, y: 62), controlPoint: CGPoint(x: 140, y: 93))</pre><pre>//畫第三根頭髮<br><strong>hairPath.move(to: CGPoint(x: 140, y: 125))<br></strong>hairPath.addQuadCurve(to: CGPoint(x: 162, y: 62), controlPoint: CGPoint(x: 140, y: 93))</pre><pre>//畫第四根頭髮<br><strong>hairPath.move(to: CGPoint(x: 140, y: 125))</strong><br>hairPath.addQuadCurve(to: CGPoint(x: 170, y: 76), controlPoint: CGPoint(x: 148, y: 93))</pre><p>畫左半身，第一條曲線的終點<strong>(x: 60, y: 200)</strong>是下一條直線的起點，直線的終點是<strong>(x: 58, y: 400)</strong></p><pre>//左半身</pre><pre><strong>let</strong> leftBodyPath = UIBezierPath()</pre><pre>leftBodyPath.move(to: CGPoint(x: 140, y: 125))</pre><pre>leftBodyPath.addQuadCurve<strong>(to: CGPoint(x: 60, y: 200)</strong>, controlPoint: CGPoint(x: 65, y: 133))</pre><pre>leftBodyPath.addLine<strong>(to: CGPoint(x: 58, y: 400))</strong></pre><pre>leftBodyPath.addQuadCurve(to: CGPoint(x: 100, y: 463), controlPoint: CGPoint(x: 54, y: 465))</pre><pre>leftBodyPath.addLine(to: CGPoint(x: 100, y: 480))</pre><pre>leftBodyPath.addQuadCurve(to: CGPoint(x: 83, y: 500), controlPoint: CGPoint(x: 88, y: 490))</pre><pre>leftBodyPath.addLine(to: CGPoint(x: 134, y: 500))</pre><pre>leftBodyPath.addLine(to: CGPoint(x: 134, y: 465))</pre><pre>leftBodyPath.addLine(to: CGPoint(x: 140, y: 465))</pre><p>回到畫頭髮的部分，<strong>close()</strong>是自動連“直線”回起點座標，所以如果畫到髮尾用close()回到髮根可以嗎？<br>也不是不行～只是頭髮會變的像草根一樣粗硬！原圖以純曲線畫頭髮，但如果用了<strong>close()</strong>會畫出完美直線回起點座標，反而畫出一個完美弓形</p><pre>//畫第一根頭髮<br><strong>hairPath.move(to: CGPoint(x: 140, y: 125))</strong><br>hairPath.addQuadCurve(to: CGPoint(x: 112, y: 76), controlPoint: CGPoint(x: 133, y: 93))<br><strong>hairPath.close()</strong></pre><pre>//CAShapeLayer顯示頭髮</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*3aysEM92Y7J5ot7t3OlNTw.png" /><figcaption>左邊第一根頭髮變弓型</figcaption></figure><p>而畫長方形，因爲是直線，所以可以用close()回起點</p><pre>//畫眼鏡架: 畫一個長條的長方形</pre><pre>let glassesFramePath = UIBezierPath()<br><strong>glassesFramePath.move(to: CGPoint(x: 54, y: 190))</strong><br>glassesFramePath.addLine(to: CGPoint(x: 230, y: 190))<br>glassesFramePath.addLine(to: CGPoint(x: 230, y: 210))<br>glassesFramePath.addLine(to: CGPoint(x: 54, y: 210))<br><strong>glassesFramePath.close()</strong></pre><pre>//CAShapeLayer顯示眼鏡架: 一個長條的長方形</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*j4AV5kmnX3YACNRVIu7mAg.png" /></figure><h4><strong>CAShapeLayer將路徑變成形狀</strong></h4><p>繪製的時候有個疑問：UIBezierPath路徑要畫到什麼程度才能呼叫一次CAShapeLayer變成形狀呢？如果將小小兵吃切成超多部位繪製，是不是每一個部位就要呼叫一次？</p><p>答案是yes也是no。yes的原因是，如果希望調整各部位的屬性—線條顏色<strong>strokeColor</strong>、線條寬度<strong>lineWidth、</strong>內部填色<strong>fillColor</strong>時，就需要各部位畫完後呼叫一次CAShapeLayer。<br>no的原因是，例如小小兵外框、瞳孔、鞋子等都相同顏色、線寬時，UIBezierPath畫完後統一呼叫一次CAShapeLayer也ＯＫ。此種情況下，<br>部位之間筆畫沒有連續時，前一部位畫完，用<strong>move(to:)</strong>到下一部位繼續繪製即可。如四根頭毛日後沒有打算讓他分別挑染，所以共同呼叫一個CAShapeLayer()</p><pre>//用UIBezierPath畫第一、二、三、四根頭髮<br></pre><pre>//呼叫一次CAShapeLayer顯示全四根頭髮</pre><pre><strong>let</strong> minionLineColor = UIColor(red: 62/255, green: 57/255, blue: 53/255, alpha: 1)</pre><pre><strong>let</strong> hairLayer = CAShapeLayer()<br>hairLayer.path = hairPath.cgPath<br>hairLayer.strokeColor = minionLineColor.cgColor<br>hairLayer.lineWidth = 8<br>view.layer.addSublayer(hairLayer)</pre><h4>製作小小兵右半邊部位，用CGAffineTransform做位移和翻轉</h4><p>製作小小兵右半邊時，同樣要幫右半部位呼叫CAShapeLayer顯示形狀，並且讓右半路徑＝左半路徑，再設定與左半部位相同的屬性。<br>以身體舉例，小小兵的左半身路徑＝右半身路徑，並且左右相反。所以要先移動，再用<strong>scaledBy(x: -1, y: 1)</strong>做鏡像翻轉。</p><p><strong>let moveDistance = leftBodyPath.bounds.maxX*2</strong>指的是：<br>讓移動距離＝構成右半身的所有座標(包含控制點)中，最大的X座標值*2</p><pre>frame：該view在superView座標系統中的位置和大小。(參照點是superView座標系統）<br>bounds：該view在本身座標系統中的位置和大小。（參照點是本身座標系統）</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*5017Et_0j0QErplZbVR5AA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*akiXhVB-Zg2lLD62FI81Wg.jpeg" /><figcaption>先移動(左圖)，再水平翻轉(右圖)</figcaption></figure><pre>//畫完左半身體leftBodyPath</pre><pre>//呼叫一次CAShapeLayer顯示左半身</pre><pre>let leftBodyLayer = CAShapeLayer()<br>leftBodyLayer.path = leftBodyPath.cgPath<br>leftBodyLayer.strokeColor = minionLineColor.cgColor<br>leftBodyLayer.fillColor = bodyColor.cgColor<br>leftBodyLayer.lineWidth = 8<br>view.layer.addSublayer(leftBodyLayer)<br></pre><pre>//右半身：水平移動＋翻轉左半邊身體</pre><pre>let rightBodyLayer = CAShapeLayer()</pre><pre>rightBodyLayer.path = leftBodyPath.cgPath</pre><pre><strong>let moveDistance = leftBodyPath.bounds.maxX*2</strong></pre><pre><strong>let transform = CGAffineTransform(translationX: moveDistance, y: 0).scaledBy(x: -1, y: 1)</strong></pre><pre><strong>rightBodyLayer.setAffineTransform(transform)</strong></pre><pre>rightBodyLayer.strokeColor = minionLineColor.cgColor</pre><pre>rightBodyLayer.fillColor = bodyColor.cgColor</pre><pre>rightBodyLayer.lineWidth = 8</pre><pre>view.layer.addSublayer(rightBodyLayer)</pre><h4>關於畫圓</h4><p>小小兵的圓型鏡框＋眼睛＋瞳孔是使用UIBezierPath畫圓</p><pre>// 左圓鏡框<strong><br>let leftGlassesPath = UIBezierPath(arcCenter: CGPoint(x: 105, y: 200), radius: 35, startAngle: .pi/180 * 0, endAngle: .pi/180 * 360, clockwise: true)</strong></pre><pre>let leftGlassesLayer = CAShapeLayer()<br>leftGlassesLayer.path = leftGlassesPath.cgPath<br>leftGlassesLayer.strokeColor = minionLineColor.cgColor<br>leftGlassesLayer.fillColor = minionLineColor.cgColor<br>leftGlassesLayer.lineWidth = 8<br>view.layer.addSublayer(leftGlassesLayer)</pre><pre>//左眼<br><strong>let leftEyePath = UIBezierPath(arcCenter: CGPoint(x: 105, y: 200), radius: 23, startAngle: .pi/180 * 0, endAngle: .pi/180 * 360, clockwise: true)</strong></pre><pre>let leftEyeLayer = CAShapeLayer()<br>leftEyeLayer.path = leftEyePath.cgPath<br>leftEyeLayer.strokeColor = UIColor.white.cgColor<br>leftEyeLayer.fillColor = UIColor(white: 1, alpha: 1).cgColor<br>leftEyeLayer.lineWidth = 8<br>view.layer.addSublayer(leftEyeLayer)</pre><pre>//左曈孔<br><strong>let leftPupilPath = UIBezierPath(arcCenter: CGPoint(x: 110, y: 200), radius: 8, startAngle: .pi/180 * 0, endAngle: .pi/180 * 360, clockwise: false)</strong></pre><pre>let leftPupilLayer = CAShapeLayer()<br>leftPupilLayer.path = leftPupilPath.cgPath<br>leftPupilLayer.strokeColor = minionLineColor.cgColor<br>leftPupilLayer.fillColor = minionLineColor.cgColor<br>leftPupilLayer.lineWidth = 8<br>view.layer.addSublayer(leftPupilLayer)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*3XWC1z-tp9_vAUffJrRCPA.png" /></figure><p>褲子Logo則生成一個圓型view，在裡面用UIBezierPath畫菱形，使菱形跟褲子一樣顏色</p><pre><strong>let circleView = UIView(frame: CGRect(x: 113, y: 373.5, width: 56, height: 56))</strong></pre><pre><strong>circleView.layer.cornerRadius = circleView.frame.size.width / 2</strong></pre><pre>circleView.backgroundColor = minionLineColor</pre><pre>view.addSubview(circleView)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*qyx1Oqh-59WoFeRBlrM9FQ.png" /></figure><h4>利用 CAGradientLayer &amp; mask 讓 CAShapeLayer 繪製的形狀變漸層 ＆使用 CABasicAnimation 設定動畫</h4><p>因為篇幅太長，請見下一篇文章</p><p><a href="https://medium.com/@judy840103/%E9%81%8B%E7%94%A8-cagradientlayer-cabasicanimation%E5%81%9A%E5%AD%97%E6%AF%8D%E6%95%88%E6%9E%9C-899d1c0c361d">運用 CAGradientLayer、 CABasicAnimation做字母效果</a></p><h4>其他</h4><p>這次繪圖時發現命名真的重要性，因為一下是畫path、layer，還要包裝成function，所以特別注意了命名規則。</p><p>畫路徑的時候因為細分太多部位了，所以UIBezierPath相關命名［部位＋path(型別名稱)］;<br>CAShapeLayer則命名［部位＋layer(型別名稱)］</p><p>func代表的是命令、方法(method)或是行為(behavior)，程式尾呼叫func的目的是“生成”小小兵部位，所以func的命名是［動詞＋部位］，包成func的好處是可以自由選擇要生成的部位</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CdzF3X9dW1nNJlwMEV6C2g.gif" /></figure><h4>附上小小兵程式碼</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8b91d12a756d0017dd1d7e0002781fa/href">https://medium.com/media/d8b91d12a756d0017dd1d7e0002781fa/href</a></iframe><p><strong>UIBezierPath繪圖參考</strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E7%94%A8%E7%A8%8B%E5%BC%8F%E7%95%AB%E5%87%BA%E5%99%97%E6%B5%AA%E5%BD%A9%E8%99%B9%E6%97%97-uibezierpath%E7%B9%AA%E5%9C%96%E7%B7%B4%E7%BF%92-9061fe131ce1">用程式畫出噗浪彩虹旗─UIBezierPath繪圖練習</a></p><p><strong>CAShapeLayer相關參考</strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-cashapelayer-%E5%B0%87-view-%E8%AE%8A%E6%88%90%E4%BB%BB%E6%84%8F%E5%BD%A2%E7%8B%80-da7e5b700c70">利用 CAShapeLayer 和 mask 將 View 變成任意形狀</a></p><p><strong>CGAffineTransform的基本使用介紹</strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/83-%E5%88%A9%E7%94%A8-cgaffinetransform-%E7%B8%AE%E6%94%BE-%E4%BD%8D%E7%A7%BB%E5%92%8C%E6%97%8B%E8%BD%89-e061df9ed672">利用 CGAffineTransform 縮放，位移，旋轉和鏡像翻轉</a></p><p><strong>CGAffineTransform的進階介紹 (小小兵右半身翻轉參考)</strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-cgaffinetransform-%E6%8E%A7%E5%88%B6%E5%85%83%E4%BB%B6%E7%B8%AE%E6%94%BE-%E4%BD%8D%E7%A7%BB-%E6%97%8B%E8%BD%89%E7%9A%84%E4%B8%89%E7%A8%AE%E6%96%B9%E6%B3%95-dca1abbf9590">利用 CGAffineTransform 控制元件縮放，位移，旋轉的三種方法</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b85874ae8d06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E9%81%8B%E7%94%A8-uibezierpath-cashapelayer-%E7%B9%AA%E8%A3%BD%E5%B0%8F%E5%B0%8F%E5%85%B5-b85874ae8d06">運用 UIBezierPath、CAShapeLayer 繪製小小兵</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[運用 CAGradientLayer、 CABasicAnimation做字母效果]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E9%81%8B%E7%94%A8-cagradientlayer-cabasicanimation%E5%81%9A%E5%AD%97%E6%AF%8D%E6%95%88%E6%9E%9C-899d1c0c361d?source=rss-bf20f4bb205e------2</link>
            <guid isPermaLink="false">https://medium.com/p/899d1c0c361d</guid>
            <category><![CDATA[cabasicanimation]]></category>
            <category><![CDATA[names]]></category>
            <category><![CDATA[cagradientlayer]]></category>
            <category><![CDATA[minions]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[陳芷慧]]></dc:creator>
            <pubDate>Wed, 22 Dec 2021 18:27:29 GMT</pubDate>
            <atom:updated>2021-12-26T06:41:20.505Z</atom:updated>
            <content:encoded><![CDATA[<h4>利用 CAGradientLayer做字母漸層、CABasicAnimation設定動畫</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*pEZfdXO7EHcmkryYqbNpSQ.jpeg" /></figure><h4>上一篇文章</h4><p><a href="https://medium.com/@judy840103/%E9%81%8B%E7%94%A8-uibezierpath-cashapelayer-%E7%B9%AA%E8%A3%BD%E5%B0%8F%E5%B0%8F%E5%85%B5-b85874ae8d06">運用 UIBezierPath、CAShapeLayer 繪製小小兵</a></p><h4>製作檔案</h4><p><a href="https://github.com/doobll/minion_Drawing">GitHub - doobll/minion_Drawing</a></p><h4>本次繪製用到以下功能：</h4><ol><li>利用UIBezierPath繪製路徑</li><li>利用CAShapeLayer產生形狀</li><li><strong>利用 CAGradientLayer &amp; mask 讓 CAShapeLayer 繪製的形狀變漸層</strong></li><li><strong>使用 CABasicAnimation 設定動畫</strong></li></ol><h4>利用 CAGradientLayer &amp; mask 讓 CAShapeLayer 繪製的形狀變漸層</h4><p>再來就是幫小小兵的名字KEVIN加漸層了！想呈現字母內顏色漸層 ＆ 字母邊框漸層兩種效果，取決於CAShapeLayer的fillColor屬性有無顏色</p><p>eLayer.fillColor = UIColor.clear.cgColor →無顏色</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*FxRPv3wNZ3eRqL5OUWVO4A.png" /></figure><p>首先在生成CAGradientLaye後，挑選漸層效果的顏色。我從下面網站選了三個顏色，按一下顏色組合下方的分享按鈕可以複製每個顏色的RGB數值，很方便！</p><p>漸層放三個顏色，<strong>gradientLayer.locations</strong>的array就要放三個值，各代表漸層顏色的分布比例，數值範圍為0–1。我設定[0.09, 0.15, 0.2] 代表左圖第一藍色到中間藍色的漸層從0開始、0.09結束; 中間藍色到黃色的漸層從0.15開始、0.2結束。</p><p><strong>要注意</strong>locations的array中的數值要越來越大，並且有幾個顏色就要有幾個數值。</p><pre>let gradientLayer = CAGradientLayer()</pre><pre><strong>let nameGradientColor = [<br>CGColor(red: 10/255, green: 25/255, blue: 49/255, alpha: 1),<br>CGColor(red: 24/255, green: 90/255, blue: 219/255, alpha: 1),<br>CGColor(red: 255/255, green: 201/255, blue: 71/255, alpha: 1)]</strong></pre><pre>gradientLayer.colors = nameGradientColor</pre><pre><strong>gradientLayer.locations = [0.09, 0.15, 0.2]</strong></pre><pre>gradientLayer.frame = CGRect(x: 0, y: 0, width: 500, height: 500)</pre><pre>view.layer.addSublayer(gradientLayer)</pre><pre>gradientLayer.mask = eLayer</pre><p><a href="https://instahues.com/">Color Palettes and Color Gradient Tool | InstaHues</a></p><p>另外因為我事後才想到要幫字母加漸層效果，所以我先畫了字母的路徑和形狀後，才把eLayer 設成 gradientLayer 的 mask，造成字母E消失！為什麼會這樣？？OMG</p><p>因為我在繪製字母E時使用了<strong>view的座標</strong>去設定路徑位置 (此時view還是eLayer的superView)，但之後因為要將eLayer 設成 gradientLayer 的 mask (想像成gradientLayer變成eLayer的superView)，導致<strong>gradientLayer上的字母E 路徑</strong>走的是<strong>view的座標系統</strong>，換句話說，字母E的路徑應該要gradientLayer的左上角(0,0)開始繪製才對！哎，所以字母無法顯現，更不用說還要求他漸層了！</p><pre><strong>view.layer.addSublayer(gradientLayer)</strong></pre><pre><strong>gradientLayer.mask = eLayer</strong></pre><blockquote>其實正確的製作順序是先有漸層Layer，然後在Layer上畫路徑才對啊——————</blockquote><p>但木已成舟，既然現在沒辦法硬逼 eLayer 的 (0,0) 對應到 gradientLayer 的左上角 (0,0)，不重畫的方法是，將<strong>gradientLayer</strong>的(x,y)座標設(0,0)，讓他對齊view的左上角 (0,0)後，把frame尺寸設大一點如 width: 500, height: 500，讓字母mask的路徑部分顯現出來。</p><pre><strong>let</strong> ePath = UIBezierPath()</pre><pre>//不小心依照view為基準畫路徑的座標</pre><pre>ePath.move(to: CGPoint(x: 249, y: 57))<br>ePath.addLine(to: CGPoint(x: 228, y: 57))<br>ePath.addLine(to: CGPoint(x: 228, y: 81))<br>ePath.addLine(to: CGPoint(x: 249, y: 81))<br>ePath.move(to: CGPoint(x: 230, y: 69))<br>ePath.addLine(to: CGPoint(x: 247, y: 69))</pre><pre>//顯示Ｅ字母的CAShapeLayer</pre><pre>let eLayer = CAShapeLayer()<br>eLayer.path = ePath.cgPath<br>eLayer.strokeColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1).cgColor<br>eLayer.lineWidth = 8<br>eLayer.fillColor = UIColor.clear.cgColor<br>view.layer.addSublayer(eLayer)</pre><pre>let gradientLayer = CAGradientLayer()</pre><pre>let nameGradientColor = [<br>CGColor(red: 10/255, green: 25/255, blue: 49/255, alpha: 1),<br>CGColor(red: 24/255, green: 90/255, blue: 219/255, alpha: 1),<br>CGColor(red: 255/255, green: 201/255, blue: 71/255, alpha: 1)]</pre><pre>gradientLayer.colors = nameGradientColor</pre><pre>gradientLayer.locations = [0.09, 0.15, 0.2]</pre><pre><strong>gradientLayer.frame = CGRect(x: 0, y: 0, width: 500, height: 500)</strong></pre><pre>view.layer.addSublayer(gradientLayer)</pre><pre>gradientLayer.mask = eLayer</pre><h4>使用 CABasicAnimation 設定動畫</h4><p>先說明以下動畫沒有加上viewDidLoad，所以不會在畫面一啟動就開始跑動畫。要特別壓option+command+p去跑預覽。</p><p><a href="https://developer.apple.com/documentation/quartzcore/cabasicanimation">CABasicAnimation | Apple Developer Documentation</a></p><p>CABasicAnimation可以實現位移、透明度、顏色、拉伸等動畫效果。這些動畫效果會由傳入的keyPath參數決定。我們用KEVIN的名字來測試，用前四個字母分別測試不同的動畫效果。</p><p>animation.duration設定動畫持續時間，以秒為單位。以下例子都沒有動到秒數</p><blockquote><strong>字母 K</strong></blockquote><p><strong>transform.scale.x</strong>會拉伸Layer，將字母K的X座標由2到1拉伸<br>toValue的1是K原先設定的座標位置。kLayer從畫右拉伸移動到原設定位置。</p><pre>let animation = CABasicAnimation(keyPath: <strong>“transform.scale.x”</strong>)</pre><pre>animation.fromValue = 2</pre><pre>animation.toValue = 1</pre><pre>animation.duration = 3</pre><pre>kLayer.add(animation, forKey: nil)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/0*M2taOSb59_gj4_vM.gif" /><figcaption>animation.fromValue = 2 animation.toValue = 1</figcaption></figure><p><strong>稍微調整數值試試效果</strong></p><p>雖然沒有調整速度，但因為距離變遠，所以速度也變快了</p><pre>animation.fromValue = 3</pre><pre>animation.toValue = 0</pre><pre>animation.duration = 3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*maWDukMWYrISxhvB.gif" /><figcaption>animation.fromValue = 3 animation.toValue = 0</figcaption></figure><blockquote><strong>字母 E</strong></blockquote><p><strong>strokeEnd</strong>代表顯示從 CABasicAnimation 路徑的起點畫線到終點的動畫效果。fromValue = 0是路徑起點，toValue = 1是路徑終點。畫面從開頭的空白到按照UIBezierPath的路徑順序，從起點到終點的跑出動畫。</p><pre>let animation = CABasicAnimation(keyPath: <strong>“strokeEnd”</strong>)</pre><pre>animation.fromValue = 0</pre><pre>animation.toValue = 1</pre><pre>animation.duration = 3</pre><pre>eLayer.add(animation, forKey: nil)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/0*xXaaXAK-keAMg6kR.gif" /></figure><p><strong>稍微調整數值試試效果</strong></p><p>把fromValue和toValue的值倒過來，畫面從開頭的E開始一筆一劃的消失</p><pre>animation.fromValue = 1</pre><pre>animation.toValue = 0</pre><pre>animation.duration = 3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/0*p_25fpAbDgtXy9UJ.gif" /></figure><blockquote><strong>字母 V</strong></blockquote><p><strong>opacity </strong>會讓一個 layer <strong>從 </strong>0 到 1 的淡入，反之則淡出</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/0*Vdzt7Ii_HR5tmPTo.gif" /><figcaption>淡入</figcaption></figure><pre>let animation = CABasicAnimation(keyPath:<strong> “opacity”</strong>)</pre><pre>animation.fromValue = 0</pre><pre>animation.toValue = 1</pre><pre>animation.duration = 3</pre><pre>vLayer.add(animation, forKey: nil)</pre><blockquote><strong>字母 I</strong></blockquote><p><strong>position</strong>可以控制一個layer要從某座標移動到某座標，是設定讓layer回到原本位置。從開頭Ｉ在[0, 40]的位置，移動到iLayer原本的位置[0, 0]</p><p>因為iLayer貼在漸層layer上，所以移動時出乎意料做出了變色效果～</p><pre>let animation = CABasicAnimation(keyPath: <strong>“position”</strong>)</pre><pre>animation.fromValue = [0, 40]</pre><pre>animation.toValue = [0, 0]</pre><pre>animation.duration = 1</pre><pre>iLayer.add(animation, forKey: nil)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/0*bxJHK8Pyi6xQeE-C.gif" /></figure><h4>動畫成品</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/0*H4008dt_j5lNimnk.gif" /></figure><h4>最後附上漸層＆動畫效果的程式碼</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bc9eb2d41f4101e9b3feb0e11179829/href">https://medium.com/media/2bc9eb2d41f4101e9b3feb0e11179829/href</a></iframe><p><strong>漸層方向、位置參考</strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-cagradientlayer-%E8%A3%BD%E4%BD%9C%E6%BC%B8%E5%B1%A4-e86cee69f3a0">利用 CAGradientLayer 製作漸層</a></p><p><strong>繪製的形狀加上漸層效果</strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-mask-%E8%AE%93-cashapelayer-%E7%B9%AA%E8%A3%BD%E7%9A%84%E5%BD%A2%E7%8B%80%E6%BC%B8%E5%B1%A4-6738910f43bc">利用 CAGradientLayer &amp; mask 讓 CAShapeLayer 繪製的形狀變漸層</a></p><p><strong>把線條變成動畫參考</strong></p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84%E8%A9%A6%E7%85%89-%E5%8B%87%E8%80%85%E7%9A%84-100-%E9%81%93-swift-ios-app-%E8%AC%8E%E9%A1%8C/%E5%88%A9%E7%94%A8-cabasicanimation-cashapelayer-%E7%B9%AA%E8%A3%BD%E7%B7%9A%E6%A2%9D%E5%8B%95%E7%95%AB-dc08b4db4726">#82 利用 CABasicAnimation &amp; CAShapeLayer 繪製線條動畫</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=899d1c0c361d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E9%81%8B%E7%94%A8-cagradientlayer-cabasicanimation%E5%81%9A%E5%AD%97%E6%AF%8D%E6%95%88%E6%9E%9C-899d1c0c361d">運用 CAGradientLayer、 CABasicAnimation做字母效果</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[設定 GitHub 專案的預覽圖片]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E8%A8%AD%E5%AE%9A-github-%E5%B0%88%E6%A1%88%E7%9A%84%E9%A0%90%E8%A6%BD%E5%9C%96%E7%89%87-80e22cec4f59?source=rss-bf20f4bb205e------2</link>
            <guid isPermaLink="false">https://medium.com/p/80e22cec4f59</guid>
            <category><![CDATA[thumbnail]]></category>
            <category><![CDATA[links]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[陳芷慧]]></dc:creator>
            <pubDate>Wed, 22 Dec 2021 08:13:00 GMT</pubDate>
            <atom:updated>2021-12-22T14:54:18.576Z</atom:updated>
            <content:encoded><![CDATA[<h4>分享連結時顯示喜歡的預覽照片</h4><h4>進到要修改預覽圖片的Github專案連結，在畫面右上角的三個小點，選擇Settings</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QChonC2BL8axGkgm-hrZ7g.png" /></figure><h4>在Settings的Social preview下選擇Edit&gt;upload an Image</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7guOda5OXQqDHM7PuEX9KQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCwaNqW6bj2RJmSsIDzsBg.png" /></figure><h4>完成以上步驟就大功告成囉！來看看效果</h4><p>據說設定完成要過幾個小時後才會看到效果～</p><p><a href="https://github.com/doobll/-HealthApp">GitHub - doobll/-HealthApp</a></p><h4>參考文章/檔案</h4><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E8%A8%AD%E5%AE%9A-github-%E5%B0%88%E6%A1%88%E7%9A%84%E9%A0%90%E8%A6%BD%E5%9C%96%E7%89%87-86c38abfd1dc">設定 GitHub 專案的預覽圖片</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E6%90%AD%E9%85%8D-sketch-zeplin-%E8%A3%BD%E4%BD%9C-ios-%E7%9A%84%E5%81%A5%E5%BA%B7-app-%E5%92%8C-app-store-%E7%95%AB%E9%9D%A2-c6ef2b45ad7">搭配 sketch &amp; zeplin 製作 iOS 的健康 App 和 App Store 畫面</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80e22cec4f59" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E8%A8%AD%E5%AE%9A-github-%E5%B0%88%E6%A1%88%E7%9A%84%E9%A0%90%E8%A6%BD%E5%9C%96%E7%89%87-80e22cec4f59">設定 GitHub 專案的預覽圖片</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>