如何為圓角添加陰影

在iOS中為UIView添加陰影還是比較簡(jiǎn)單的,只需要設(shè)置layershadow屬性就可以了,但是問(wèn)題在于設(shè)置陰影之后,必須設(shè)置masksToBoundsNO,而圓角圖片則要求masksToBounds必須為YES,兩者相互沖突,會(huì)導(dǎo)致無(wú)法正確的添加陰影。
正確的做法是先創(chuàng)建一個(gè)透明的UIView,并添加陰影,設(shè)置masksToBoundsNO
然后在透明的UIView上添加圓角圖片,在subView上設(shè)置masksToBoundsYES
這樣,就可以完美實(shí)現(xiàn)對(duì)應(yīng)的陰影了。

        let baseView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        // add the shadow to the base view
        baseView.backgroundColor = UIColor.clear
        baseView.layer.shadowColor = UIColor.black.cgColor
        baseView.layer.shadowOffset = CGSize(width: 3, height: 3)
        baseView.layer.shadowOpacity = 0.7
        baseView.layer.shadowRadius = 4.0
        self.view.addSubview(baseView)
        
        // add any other subcontent that you want clipped
        let otherSubContent = UIImageView()
        otherSubContent.image = UIImage(named: "lion")
        otherSubContent.frame = baseView.bounds
        otherSubContent.layer.masksToBounds = true
        otherSubContent.layer.cornerRadius = 50
        baseView.addSubview(otherSubContent)

效果如下圖:


屏幕快照 2017-08-03 下午2.53.46.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 在iOS中隨處都可以看到絢麗的動(dòng)畫(huà)效果,實(shí)現(xiàn)這些動(dòng)畫(huà)的過(guò)程并不復(fù)雜,今天將帶大家一窺iOS動(dòng)畫(huà)全貌。在這里你可以看...
    F麥子閱讀 5,141評(píng)論 5 13
  • 在iOS中隨處都可以看到絢麗的動(dòng)畫(huà)效果,實(shí)現(xiàn)這些動(dòng)畫(huà)的過(guò)程并不復(fù)雜,今天將帶大家一窺ios動(dòng)畫(huà)全貌。在這里你可以看...
    每天刷兩次牙閱讀 8,562評(píng)論 6 30
  • //設(shè)置尺寸為屏幕尺寸的時(shí)候self.window = [[UIWindow alloc] initWithFra...
    LuckTime閱讀 833評(píng)論 0 0
  • { 11、核心動(dòng)畫(huà) 需要簽協(xié)議,但是系統(tǒng)幫簽好 一、CABasicAnimation 1、創(chuàng)建基礎(chǔ)動(dòng)畫(huà)對(duì)象 CAB...
    CYC666閱讀 1,589評(píng)論 2 4
  • 腦海里某天突然又冒出要畫(huà)畫(huà)的想法,希望每天打卡,能堅(jiān)持吧,生活要多點(diǎn)色彩!再一步步進(jìn)階彩鉛水彩!!
    Fancy_a787閱讀 329評(píng)論 0 0