IOS how to add shadow effect for fillet sample code

Time:2021-4-27

preface

As we all know, it’s relatively easy to add shadows to uiview in IOS. You only need to set the shadow attribute of layer. However, the problem is that after setting shadows, you must set the maskstobounds to no, while the rounded image requires that the maskstobounds must be yes. The two conflicts with each other, which will lead to incorrect shadow addition. Let’s introduce the correct effect of adding shadow to the fillet. Let’s take a look at the detailed introduction.

Let’s take a look at the renderings

The right way to do it:

First, create a transparent uiview, add shadow, and set the mask to borders to No;

Then, the rounded image is added to the transparent uiview, and the maskstobounds is set to yes on the subview;

In this way, the corresponding shadow can be perfectly realized.

Sample code


  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)

summary

The above is the whole content of this article, there are many deficiencies in this article, I hope the content of this article has a certain reference learning value for your study or work, if you have any questions, you can leave a message to exchange, thank you for your support for developer.

Recommended Today

Looking for frustration 1.0

I believe you have a basic understanding of trust in yesterday’s article. Today we will give a complete introduction to trust. Why choose rust It’s a language that gives everyone the ability to build reliable and efficient software. You can’t write unsafe code here (unsafe block is not in the scope of discussion). Most of […]