如何在swift3.0.1中给imageView添加阴影同时带有圆角

2024-04-06

我想给一个imageView同时加上圆角的阴影,但是我失败了。


这是我的解决方案

基本思想:

  1. 使用额外视图(例如 AView)作为图像视图的超级视图(对于那些您愿意拥有阴影的视图)并将该视图类分配给DGShadoView
  2. 将图像视图固定到AView(超级视图)从左、右、上、下,常数为 5
  3. 设置背景颜色AView to 颜色清晰 来自 Storybosrd 的财产检查员,这很重要

内部想法: 在这里,我们在 Aview 上几乎在边界上使用贝塞尔路径,并将所有圆角属性和阴影属性设置为该路径,并将目标图像视图放置在该路径边界中

@IBDesignable
class DGShadoView:UIView {

override func draw(_ rect: CGRect) {
    self.rect = rect
    decorate(rect: self.rect)
}

func decorate(rect:CGRect) {


    //self.backgroundColor = UIColor.clear 
    //IMPORTANT: dont forgot to set bg color of your view to clear color from story board's property inspector 

    let ref = UIGraphicsGetCurrentContext()
    let contentRect = rect.insetBy(dx: 5, dy: 5);
    /*create the rounded oath and fill it*/
    let roundedPath = UIBezierPath(roundedRect: contentRect, cornerRadius: 5)
    ref!.setFillColor("your color for background".cgColor)
    ref!.setShadow(offset: CGSize(width:0,height:0), blur: 5, color: "your color for shado".cgColor)
    roundedPath.fill()

    /*draw a subtle white line at the top of view*/
    roundedPath.addClip()
    ref!.setStrokeColor(UIColor.red.cgColor)
    ref!.setBlendMode(CGBlendMode.overlay)
    ref!.move(to: CGPoint(x:contentRect.minX,y:contentRect.minY+0.5))
    ref!.addLine(to: CGPoint(x:contentRect.maxX,y:contentRect.minY+0.5))
}

}

Update

延伸法

还有另一种方法。只需创建一个空类并粘贴以下 UIImageView 扩展代码,将此子类分配给您阴影所在的 ImageView。

import UIKit

class DGShadowView: UIImageView {

    @IBInspectable var intensity:Float = 0.2{
        didSet{
           setShadow()
        }
    }
    override func layoutSubviews()
    {
        super.layoutSubviews()
        setShadow()
    }

    func setShadow(){
        let shadowPath = UIBezierPath(rect: bounds)
        layer.masksToBounds = false
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOffset = CGSize(width: 0.0, height: 0.3)
        layer.shadowOpacity = intensity
        layer.shadowPath = shadowPath.cgPath
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在swift3.0.1中给imageView添加阴影同时带有圆角 的相关文章

随机推荐