swift4.0 代码设置阴影

有的时候,项目中会用到阴影的效果,增加立体感。我们可以让设计师给出切图,用图片填充。我们还可以使用几句代码来实现简单的阴影效果。
实现效果图展示一:


image.png

实现效果图展示一:


11.png

关键代码:

        firstView.layer.shadowColor = UIColor.purple.cgColor
        firstView.layer.shadowOffset = CGSize(width: 0, height: 20)
        firstView.layer.shadowRadius = 10
        firstView.layer.shadowOpacity = 0.1

简单解释下:
shadowColor: 阴影颜色
shadowOffset:阴影的范围(自己试下看看效果就晓得了)
shadowRadius: 阴影的圆角
shadowOpacity:阴影的透明度

详细步骤:

  1. 在storyboard上搭建简单的UI
image.png

2.拖线关联


image.png
  1. 设置阴影以及圆角
//
//  ViewController.swift
//  TestShadow
//
//  Created by iOS on 2018/9/14.
//  Copyright © 2018年 weiman. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var firstView: UIView!
    @IBOutlet weak var purpleView: UIView!
    @IBOutlet weak var blueView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup() {
        firstView.layer.shadowColor = UIColor.purple.cgColor
        firstView.layer.shadowOffset = CGSize(width: 0, height: 20)
        firstView.layer.shadowRadius = 10
        firstView.layer.shadowOpacity = 0.1
        
        purpleView.layer.cornerRadius = 10
        purpleView.layer.masksToBounds = true
        blueView.layer.cornerRadius = 10
        blueView.layer.masksToBounds = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

注意:
把firstview的背景颜色设置成透明色,也就是clearColor,效果是

image.png

把firstview设置成白色,效果是

image.png

你可能感兴趣的:(swift4.0 代码设置阴影)