起因是項(xiàng)目里有一個(gè)引導(dǎo)頁面需要實(shí)現(xiàn)鏤空的效果
于是我想到了使用透明背景圖,然后使用貝塞爾曲線畫出來一個(gè)圓角矩形并填使用顏色充整個(gè)View
//在draw(_ rect: CGRect)里進(jìn)行繪制
override func draw(_ rect: CGRect) {
//這是頁面里的透明矩形
let myRect = CGRect(x: kScreenWidth - 162 - 12, y: 385, width: 162, height: 64)
let path = UIBezierPath.init(rect: rect)//這里得到的rect就是整個(gè)View的rect
let circlePath = UIBezierPath.init(roundedRect: myRect, cornerRadius: 8)//這一步是為了得到圓角矩形的path
path.append(circlePath)
//這里使用奇偶填充規(guī)則(判斷一個(gè)閉合的path)
//具體內(nèi)容在http://www.lovecqmh.cn/?p=27
path.usesEvenOddFillRule = true
let fillLayer = CAShapeLayer.init()
fillLayer.path = path.cgPath
fillLayer.fillRule = kCAFillRuleEvenOdd
fillLayer.fillColor = UIColor.init(hex: 0x000000).withAlphaComponent(0.6).cgColor
fillLayer.opacity = 0.5
self.layer.addSublayer(fillLayer)
//下面是坑
//之前設(shè)置圖片的時(shí)候使用了imageView白胀,并添加在了View上鳄橘,但是這么做的后果就是
//draw(_ rect: CGRect)繪制的時(shí)候會(huì)把view上圖片等其他空間顏色遮擋導(dǎo)致顏色與UI圖
//上不一致情臭,所以我使用了layer 飒货,在繪制完透明矩形之后再添加圖片在self.layer上也就
//不會(huì)出現(xiàn)遮擋的問題了
let imageLayer = CALayer.init()
imageLayer.frame = CGRect(x: kScreenWidth - 162 - 12, y: 464, width: 162, height: 116)
imageLayer.contents = UIImage.init(named: "test_sign")?.cgImage//這里要記得寫cgImage不然會(huì)顯示不出來
self.layer.addSublayer(imageLayer)
}