進階的調色 App — 多個區塊的著色

調色 App 是個滿適合 iOS App 開發初學者的有趣練習,同學們常常精心找尋自己喜歡的圖片,用程式為圖片的去背區塊填上美麗的色彩。

不過時常有同學問我,有沒有可能為不同區塊填上不同的色彩呢 ? 比方為可愛的 Mickey 換裝,換上綠色衣服和紅色手套呢 ?

其實是可以的 ,不過步驟比較複雜,關鍵在於另外加入我們要著色的區塊圖片,比方 Mickey 的紅色衣服和白色手套。有興趣的朋友可參考以下的步驟說明:

1 將圖片加到 Xcode 專案的 Assets.xcassets。

我們需準備原始圖片和填色區塊的圖片。以 Mickey 為例,我們需準備 Mickey 的原圖,衣服的圖片,以及手套的圖片。

(1) Mickey 的原始圖片。

(2) Mickey 的衣服圖片。

將 Mickey 的原始圖片去背,只留下紅色衣服的部分。

去背的方法可參考以上連結。為了只保留紅色衣服,我們可先用 instant alpha 選取紅色衣服,然後再點選 Edit > Invert Selection,接著再點選 Edit > Cut 將衣服以外的區塊去得一乾二淨。

(3) Mickey 的手套圖片。

將 Mickey 的原始圖片去背,只留下白色手套的部分。

2 在 storyboard 的畫面上加入顯示 Mickey 原圖的 image view 和 2 個 view,讓 image view 和 2 個 view 一樣大並重疊。

因為想要著色兩個區塊,所以我們加入 2 個 view 來對應 Micky 的衣服和手套,待會我們將從程式將 view 變成著色的衣服和手套。

3 將剛剛的兩個 view 連結 outlet,生成 handView & clothesView。

class ViewController: UIViewController {   @IBOutlet weak var handView: UIView!   @IBOutlet weak var clothesView: UIView!

4 在 function viewDidLoad 裡將 handView & clothesView 變成著色的衣服和手套。

override func viewDidLoad() {   super.viewDidLoad()   var image = UIImage(named: "mickeyClothes")   let clothesImageView = UIImageView(image: image)   clothesImageView.frame = clothesView.bounds   clothesImageView.contentMode = .scaleAspectFit   clothesView.mask = clothesImageView   clothesView.backgroundColor = UIColor(red: 0, green: 222/255, blue: 0, alpha: 1)   image = UIImage(named: "mickeyHand")   let handImageView = UIImageView(image: image)   handImageView.frame = handView.bounds   handImageView.contentMode = .scaleAspectFit   handView.mask = handImageView   handView.backgroundColor = UIColor(red: 222/255, green: 0, blue: 0, alpha: 1)}

clothesView & handView 原本只是什麼都沒有的 view,它們是如何顯示衣服和手套的呢 ? 這裡的關鍵在於讓它們顯示原本圖片裡衣服和手套的區塊,然後再設定它們的 backgroundColor,即可變成著色的衣服和手套。

以 clothesView 為例,我們先用以下程式生成紅色衣服的clothesImageView。記得要讓它和 clothesView 一樣大,如此我們才能準確設定 clothesView 只顯示 clothesImageView 裡的衣服區塊。

var image = UIImage(named: "mickeyClothes")let clothesImageView = UIImageView(image: image)clothesImageView.frame = clothesView.boundsclothesImageView.contentMode = .scaleAspectFit

接著我們用 clothesView.mask = clothesImageView 讓長方形的 clothesView 只顯示 clothesImageView 裡有顏色的部分。mask 中文是遮罩的意思,經由設定 UIView 元件的 mask,我們將讓 view 只顯示 mask 裡非透明的區塊,其它部分被遮起來。因此原本長方形的 clothesView 將變成只顯示 clothesImageView 裡非透明的區塊,也就是紅色衣服的區塊。

最後我們再用 clothesView.backgroundColor = UIColor(red: 0, green: 222/255, blue: 0, alpha: 1) 設定 clothesView 的顏色,讓 clothesView 顯示的衣服區塊變成綠色。

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com