如何为圆角添加阴影

在iOS中为UIView添加阴影还是比较简单的,只需要设置layershadow属性就可以了,但是问题在于设置阴影之后,必须设置masksToBoundsNO,而圆角图片则要求masksToBounds必须为YES,两者相互冲突,会导致无法正确的添加阴影。
正确的做法是先创建一个透明的UIView,并添加阴影,设置masksToBoundsNO
然后在透明的UIView上添加圆角图片,在subView上设置masksToBoundsYES
这样,就可以完美实现对应的阴影了。

        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)

效果如下图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值