調色大師 — 蛋糕配色
Published in
6 min readApr 5, 2020
作業目的:熟練 outlet, action, UISlider, UIColor。
學習調整多個區塊的顏色。
原先將蛋糕上下分別存成png,但上色時會遮住下層圖片而無法將顏色顯示出來,所以使用Mask才能將重疊部分個別上色!
- Mask
- 準備蛋糕原圖、上層以及下層圖片後,在 storyboard 加入蛋糕 image view 和 2 個 view,並將image view 和 2 個 view調整大小及位置皆一樣
- 將蛋糕原圖放在最後面
- 設定蛋糕上下層的 View 只顯示 ImageView 裡的區塊
@IBOutlet weak var upView: UIView!
@IBOutlet weak var downView: UIView!override func viewDidLoad() {
super.viewDidLoad()//Cake Maskvar image = UIImage(named: “cakeUp”)
let upImageView = UIImageView(image: image)
upImageView.frame = upView.bounds
upImageView.contentMode = .scaleAspectFit
upView.mask = upImageView
upView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)//顯示最底層原圖顏色,所以將upView顏色與透明度先設0image = UIImage(named: “cakeDown”)
let downImageView = UIImageView(image: image)
downImageView.frame = downView.bounds
downImageView.contentMode = .scaleAspectFit
downView.mask = downImageView
downView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)}
- Segmented Contro 將蛋糕分層
var choose = "上層"@IBAction func chooseOption(_ sender: UISegmentedControl) {
choose = sender.titleForSegment(at: sender.selectedSegmentIndex)!}
- 調整 RGB 色及透明度
if choose == "上層"{upView.backgroundColor = UIColor(red: CGFloat(redSlider.value), green: CGFloat(greenSlider.value), blue: CGFloat(blueSlider.value), alpha: CGFloat(alphaSlider.value))}
- 顯示 Slider目前的數值
redLabel.text = String(format:”%.2f”,redSlider.value)
greenLabel.text = String(format:”%.2f”,greenSlider.value)
blueLabel.text = String(format:”%.2f”,blueSlider.value)
alphaLabel.text = String(format:”%.1f”,alphaSlider.value)}
- 使用亂數 random 隨機選色
@IBAction func randomAct(_ sender: Any) {let red = Float.random(in: 0.0…1.0)
let green = Float.random(in: 0.0…1.0)
let blue = Float.random(in: 0.0…1.0)
let alpha = Double.random(in: 0.0…1.0)upView.backgroundColor = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))downView.backgroundColor = UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))redLabel.text = String(format: “%.2f”,red)
greenLabel.text = String(format:”%.2f”, green)
blueLabel.text = String(format:”%.2f”, blue)alphaLabel.text = String(format: “%.1f”, alpha)redSlider.value = Float(red)
greenSlider.value = Float(green)
blueSlider.value = Float(blue)
alphaSlider.value = Float(alpha)