swift Swift - 在UIView上创建带阴影的圆形图像的扩展

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift - 在UIView上创建带阴影的圆形图像的扩展相关的知识,希望对你有一定的参考价值。

See: https://stackoverflow.com/questions/39624675/add-shadow-on-uiview-using-swift-3

Source:ViewShadow

Here is the extension with two functions of the same name, one with, the other without parameters.

import UIKit

extension UIView {
    
    // OUTPUT 1
    func dropShadow(scale: Bool = true) {
        self.layer.masksToBounds = false
        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOpacity = 0.5
        self.layer.shadowOffset = CGSize(width: 2, height: 2)
        self.layer.shadowRadius = 1
        
//        self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        self.layer.shouldRasterize = true
        self.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }
    
    // OUTPUT 2
    func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
        self.layer.masksToBounds = false
        self.layer.shadowColor = color.cgColor
        self.layer.shadowOpacity = opacity
        self.layer.shadowOffset = offSet
        self.layer.shadowRadius = radius
        
//        self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        self.layer.shouldRasterize = true
        self.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
    }
}


You call if from your view controller file like this:

  @IBOutlet weak var imageViewBG: UIView!
    @IBOutlet weak var imageViewFG: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let width:CGFloat = imageViewBG.bounds.width
        imageViewBG.layer.cornerRadius = width/2
        imageViewFG.layer.cornerRadius = width/2
        
        //imageViewBG.dropShadow()
        imageViewBG.dropShadow(color: UIColor.red, opacity: 0.5, offSet: CGSize(width: 6, height: 6), radius: 5, scale: true)
        
    }

以上是关于swift Swift - 在UIView上创建带阴影的圆形图像的扩展的主要内容,如果未能解决你的问题,请参考以下文章

Swift - 重复的 UIView

以编程方式在 UIView 上添加 UITextField Swift

使用 Swift 在单个 UIView 上同时进行多个动画

是否可以通过扩展中的 Swift 4 KeyPaths 在 UIView 上设置属性?

如何在swift中剪切uiview的边缘

在键盘上显示带有按钮的 UIView,例如在 Skype、Viber messengers(Swift、iOS)中