読者です 読者をやめる 読者になる 読者になる

角丸なUIViewに角丸な影をつける

環境: Swift3

角丸なUIViewに角丸なドロップシャドウをつけるやり方。
プレイグラウンドで確認。

f:id:xyk:20170319023445p:plain

import UIKit
import PlaygroundSupport

let baseView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
baseView.backgroundColor = UIColor(red: 255/255, green: 110/255, blue: 134/255, alpha: 1)

let shadowView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
shadowView.backgroundColor = UIColor(red: 89/255, green: 172/255, blue: 255/255, alpha: 1)
shadowView.center = baseView.center

shadowView.layer.cornerRadius = 10
shadowView.layer.masksToBounds = false

shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOpacity = 0.5 // 透明度
shadowView.layer.shadowOffset = CGSize(width: 5, height: 5) // 距離
shadowView.layer.shadowRadius = 5 // ぼかし量

// 以下、角丸パス追加とラスタライズで高速化
shadowView.layer.shadowPath = UIBezierPath(roundedRect: shadowView.bounds, cornerRadius: 10).cgPath
shadowView.layer.shouldRasterize = true
shadowView.layer.rasterizationScale = UIScreen.main.scale

baseView.addSubview(shadowView)

PlaygroundPage.current.liveView = baseView